Skip to content

Latest commit

Β 

History

History
74 lines (65 loc) Β· 1.64 KB

File metadata and controls

74 lines (65 loc) Β· 1.64 KB

Variables

Variables are the containers for storing values or expressions They are used to store data temporarily in the computer

Example

section = "3U"
console.log(section)

βš–οΈ Rules for js variables

  • Case sensitive
  • Must start with an an alphabet or underscore
  • Cannot start with a number
  • Cannot use reserved words as variables
  • Should be meaningful
  • Cannot contain space or hyphen (-)

Here are few examples:

  • score βœ…
  • _id βœ…
  • 01 🚫
  • await 🚫

πŸ“’ Declaration of varaibles

There are three methods of declaring a variable in js

  • let keyword
  • const keyword
  • var keyword
Keyword Access Assignment Initialise
let {...} Reassignable Optional
const {...} Final Required
var function Reassignable Optional

Reassignment

let count = 0
count = 1 //This works

const count = 0
count = 1 //This doesn't work

var count = 0
count = 1 //This works

Accessibility

{
  let blockVariable = "I am hidden";
  var functionVariable = "I am visible";
}

console.log(blockVariable);    //This doesn't work
console.log(functionVariable); //This works

Declearing multiple variables

// Both works
let name="Rohan" , role="Student";

let name="Rohan";
let role="Student";   

Note

  • If you assign values to variables that have not yet been declared, the variables will automatically be declared.
  x = 120; //  No error here
  • "var" has some confusing behaviors regarding scope and hoisting, so modern developers generally avoid it in favor of let and const.

previous

next