JavaScript?: var, let, and const

JavaScript: var, let, and const

If you're a JavaScript developer, you probably use var, let, or const in your code. But do you really know what's happening under the hood? Let’s break it down! ??

?? var – The Old Way

Before ES6, var was the only way to declare variables in JavaScript. But it comes with some quirks:

?? Hoisting: var declarations are hoisted to the top but without initialization.

?? Function scope: If declared inside a function, the variable exists only within that function. Otherwise, it becomes global.

?? Can be redeclared without errors.

console.log(name); // undefined (no error!)
var name = "David";
console.log(name); // "David"

if (true) {
  var age = 30;
}

console.log(age); // 30 (accessible outside the block) ??        

? let – A Safer Alternative

With ES6, let was introduced to fix some issues with var:

?? Block scope: The variable exists only within the {} block where it was declared.

?? Cannot be redeclared in the same scope.

?? Hoisted but uninitialized (causing a ReferenceError if accessed too early).

console.log(color); // ReferenceError ?

let color = "blue";        

This happens because let variables are in the Temporal Dead Zone (TDZ) until they are initialized.


??? const – For Constant Values

ES6 also introduced const, which behaves like let but with additional restrictions:

?? Must be initialized when declared.

?? Cannot be reassigned (but objects and arrays are still mutable).

?? Follows the same block scope rules as let.

const pi = 3.14; pi = 3.1415; // TypeError ?        

However, objects and arrays remain mutable:

const person = { name: "David" }; 

person.name = "Silva"; // ? Allowed!

console.log(person.name); // "Silva"        

If you truly want to make an object immutable, use Object.freeze():

const user = Object.freeze({ name: "David" }); 

user.name = "Silva"; // ? No effect 

console.log(user.name); // "David"        

  • Use let when the value needs to change
  • Use const whenever possible for safer code.
  • Avoid var, as it can lead to unexpected bugs.


要查看或添加评论,请登录

Davi Silva的更多文章

  • React Hooks? Ok, mas por que?

    React Hooks? Ok, mas por que?

    No dia 6 de fevereiro de 2019, foi lan?ada a vers?o 16.8 do React, introduzindo os hooks.

  • JavaScript, React ? Olha lá hein!

    JavaScript, React ? Olha lá hein!

    Nos últimos anos (quase quatro anos), venho trabalhando exclusivamente com desenvolvimento front-end, escrevendo código…

    4 条评论
  • Entendendo atributos privados no JavaScript/TypeScript

    Entendendo atributos privados no JavaScript/TypeScript

    O JavaScript, sendo uma linguagem de tipagem dinamica, realiza uma inferência automática de tipos. Isso significa que…

  • Understanding mutability and infer in TS

    Understanding mutability and infer in TS

    In this article, we will explain how Typescript works with mutability and inferring typings when you declare variables.…

  • Seven ways to remove elements from Arrays in JS

    Seven ways to remove elements from Arrays in JS

    It's most common when we develop code, in front or in the backend, to need to manipulate data from arrays removing…

  • 5 Javascript concepts every developer should know

    5 Javascript concepts every developer should know

    Every JavaScript developer should be familiar with these features that I am going to show in this article - modern…

  • "b" + "a" + +"a" + "a" ? Banana? What ?

    "b" + "a" + +"a" + "a" ? Banana? What ?

    JavaScript is one of the most important programming languages in the world. Whether you're a front-end or back-end…

    1 条评论
  • Capital letters? Why ?

    Capital letters? Why ?

    Do you work with React? Do you know why React components need to start with capital letters? In JSX, React components…

  • TTFB, TTI, and FCP: Do You Know What These Acronyms Mean?

    TTFB, TTI, and FCP: Do You Know What These Acronyms Mean?

    When discussing front-end applications built with React, we often encounter two primary types: SPAs (Single Page…

  • SOLID no React Native - parte 2

    SOLID no React Native - parte 2

    O acr?nimo SOLID trata de um conjunto de cinco regras no design de software. Com essas regras, podemos criar software…

    2 条评论

社区洞察

其他会员也浏览了