Sunday 3 November 2024

Variable Declarations and Assignments in JavaScript

1. Declaring Variables

Declaration is when you tell JavaScript to create a variable, but you do not necessarily assign a value to it right away.

 

Example

let myVariable;

 

Here, myVariable is declared, but it has not been assigned a value.

 

2. Assigning Variables

Assignment is when you give a declared variable a value.

 

Example

myVariable = 10;

 

Here, myVariable is assigned the value 10.

 

You can also declare and assign a variable in one step:

 

Example

 

let anotherVariable = 20;

Default Value of an Uninitialized Variable

When you declare a variable without assigning a value, it is automatically initialized with the value undefined.

 

Example

let myVar;
console.log(myVar); // Output: undefined

Initializing Multiple Variables in One Line

Yes, you can initialize multiple variables in one line by separating them with commas.

 

Example

let a = 1, b = 2, c = 3;
console.log(a, b, c); // Output: 1 2 3

 

You can also declare multiple variables without assigning values.

 

Example

 

let x, y, z;
console.log(x, y, z); // Output: undefined undefined undefined

 

Using Variables Without Declaration

In JavaScript, if you use a variable without declaring it, it becomes a global variable automatically. This practice is generally discouraged as it can lead to unintended side effects.

 

Example

 

myGlobalVar = 100; // No declaration
console.log(myGlobalVar); // Output: 100

 

However, if you use 'use strict'; at the beginning of your script or function, this behaviour is disallowed, and an error will be thrown.

 

strictDemo.js

 

'use strict';
myGlobalVar = 100; // Throws an error: myGlobalVar is not defined

 

$node strictDemo.js 
/Users/krishna/Documents/technical-documents/frontend/javascript/examples/1.introduction/strictDemo.js:2
myGlobalVar = 100; // Throws an error: myGlobalVar is not defined
            ^

ReferenceError: myGlobalVar is not defined
    at Object.<anonymous> (/Users/krishna/Documents/technical-documents/frontend/javascript/examples/1.introduction/strictDemo.js:2:13)
    at Module._compile (node:internal/modules/cjs/loader:1358:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1416:10)
    at Module.load (node:internal/modules/cjs/loader:1208:32)
    at Module._load (node:internal/modules/cjs/loader:1024:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
    at node:internal/main/run_main_module:28:49

Node.js v20.16.0

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment