Javascript – Variables

var: Reserved keyword
We can’t name any variable with a keyword.
Declaration & Initialization of a variable.
Uninitialized variable holds ‘undefined’ value.

Variable Hoisting: bringing the variable declaration to the top of the file.
var x; …


This content originally appeared on DEV Community and was authored by Mohammed Ali

  • var: Reserved keyword
  • We can't name any variable with a keyword.
  • Declaration & Initialization of a variable.
  • Uninitialized variable holds 'undefined' value.
Variable Hoisting: bringing the variable declaration to the top of the file.
var x;            // undefined
console.log(x);
x = 10;           // initialized
console.log(x);
Scoping:
- var: nearest fn block
- let, const : block scope i.e inside {} created by for(){}, if(){} etc.
- let, const : No hoisting, ReferenceError thrown.
- const: No rebinding of value will happen. TypeError thrown on attempt to reassig value.

{
 var x = 10;
}
console.log(x); //10

{
let y = 20;
}
console.log(y); //ReferenceError
  • Reduce overwriting-reassingning variables as they can be pointing to something else and would create a debugging mess. Not favoured in functional programming style.

Difference between let & const:

let x = {
name: "TOm"
}
x = 12; //12 object gets overwritten by value 12

let y = {
name: "TOm"
}
y = 12; //TypeError, assignment to a constant variable.

const human = { name: 'Jon'};
human.name = 'Charlie'; // its not reassignment, its talking to object for mutating its properties. It allows updating the value for object.
console.log(human.name); // Charlie


This content originally appeared on DEV Community and was authored by Mohammed Ali


Print Share Comment Cite Upload Translate Updates
APA

Mohammed Ali | Sciencx (2024-08-18T13:49:29+00:00) Javascript – Variables. Retrieved from https://www.scien.cx/2024/08/18/javascript-variables-2/

MLA
" » Javascript – Variables." Mohammed Ali | Sciencx - Sunday August 18, 2024, https://www.scien.cx/2024/08/18/javascript-variables-2/
HARVARD
Mohammed Ali | Sciencx Sunday August 18, 2024 » Javascript – Variables., viewed ,<https://www.scien.cx/2024/08/18/javascript-variables-2/>
VANCOUVER
Mohammed Ali | Sciencx - » Javascript – Variables. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/18/javascript-variables-2/
CHICAGO
" » Javascript – Variables." Mohammed Ali | Sciencx - Accessed . https://www.scien.cx/2024/08/18/javascript-variables-2/
IEEE
" » Javascript – Variables." Mohammed Ali | Sciencx [Online]. Available: https://www.scien.cx/2024/08/18/javascript-variables-2/. [Accessed: ]
rf:citation
» Javascript – Variables | Mohammed Ali | Sciencx | https://www.scien.cx/2024/08/18/javascript-variables-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.