Posted under » JavaScript on 29 October 2009
var declarations ruled since the beginning. There are issues associated with variables declared with var, though. let and const were introduced in ES6 (2015) to fix var's unpredictable behavior and scoping issues.
Scope essentially means where these variables are available for use. var declarations are globally scoped or function/locally scoped.
var greeter = "hey hi";
function newFunction() {
var hello = "hello";
}
Here, greeter is globally scoped because it exists outside a function while hello is function scoped. So we cannot access the variable hello outside of a function.
var is function-scoped: If declared inside an if block or a loop, a var variable escapes the curly braces and leaks into the parent function or global environment. let and const are block-scoped: They remain trapped inside the nearest set of curly braces {} (like loops, conditions, or function)
if (true) {
var standardVar = "I leak outside!";
let blockLet = "I am trapped here.";
}
console.log(standardVar); // Logs: "I leak outside!"
console.log(blockLet); // ReferenceError: blockLet is not defined
const creates an immutable reference. You cannot update or redeclare it. Note: Mutating an internal object property or array element assigned to a const is allowed; only direct reassignment throws an error
const wsProtocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
// const url = `${wsProtocol}fool.edu.sg/ws/socket-server/`;
const url = `${wsProtocol}${window.location.host}/ws/socket-server/`
const chatSocket = new WebSocket(url)
This JavaScript conditional expression dynamically selects the secure WebSocket protocol (wss://) with the const wsProtocol when the page loads over HTTPS, or the unsecure version (ws://) for HTTP
Now look at let. let restricts redeclaration but allows you to reassign a new value to the same variable name.
function sayHello() {
return "Hello World";
}
let a = sayHello();
let b = sayHello();
let c = sayHello();
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that if we do this: