Unit 7 ยท JavaScript

7.3Variables

On this page
  1. Types
  2. Scope
  3. Operators
JavaScript
let age = 20;            // can be reassigned
const PI = 3.14159;      // cannot be reassigned (use by default)
var old = 'avoid';       // old style; function-scoped; avoid in new code

age = 21;                // OK
// PI = 3;               // Error: Assignment to constant variable

Naming rules: letters, digits, _ and $; cannot start with a digit; no reserved words; use camelCase (totalPrice) and meaningful names.

Types

TypeExampleNotes
Number42, 3.14, NaN, InfinityIntegers and decimals are the same type
String'Hi', "Hi", `Hi ${name}`Backticks allow templates and multi-line text
Booleantrue, false
Undefinedlet x;Declared but no value
Nulllet y = null;Intentionally empty
Object{a: 1}, [1,2]Includes arrays and dates; functions are objects too (but typeof gives 'function')
BigInt, Symbol123nAdvanced
JavaScript
typeof 42;            // 'number'
typeof 'hi';          // 'string'
typeof true;          // 'boolean'
typeof undefined;     // 'undefined'
typeof null;          // 'object'  (a famous historical quirk)

Number('42');         // 42        string to number
parseInt('42px');     // 42
parseFloat('3.5kg');  // 3.5
String(99);           // '99'
Boolean('');          // false (falsy: 0, '', null, undefined, NaN, false)

const name = 'Nimal';
console.log(`Hello ${name}, 2 + 3 = ${2 + 3}`);   // template string

String methods: length, toUpperCase(), toLowerCase(), trim(), indexOf(), includes(), slice(start,end), replace(a,b), split(','), startsWith(), charAt(i).

Scope

Scope is where a variable can be used.

JavaScript
let g = 'global';            // global scope: visible everywhere

function test() {
  let local = 'function';    // function scope: visible only inside
  if (true) {
    let block = 'block';     // block scope (let and const): only inside { }
    var leaky = 'oops';      // var ignores block scope: visible in whole function
  }
  console.log(local, leaky);
  // console.log(block);     // ReferenceError
}

Rule: declare with const first; use let if you must reassign; avoid var; keep variables in the smallest scope possible.

Operators

CategoryOperators
Arithmetic+ - * / % ** (modulus, power), ++ --
Assignment= += -= *= /= %=
Comparison== (loose), === (strict), !=, !==, > < >= <=
Logical&& (and), || (or), ! (not)
String+ joins strings
Conditional (ternary)condition ? valueIfTrue : valueIfFalse
JavaScript
5 == '5';      // true  (converts type)
5 === '5';     // false (checks type too): ALWAYS prefer ===
'5' + 3;       // '53'  (string joining)
'5' - 3;       // 2     (numeric)
10 % 3;        // 1
let status = age >= 18 ? 'Adult' : 'Minor';

Try it: Write a script that asks for a price and quantity with prompt, converts to numbers, calculates 10% tax, and displays the total with alert. Use toFixed(2) for two decimals.