Skip to content

Latest commit

 

History

History
71 lines (63 loc) · 1.83 KB

File metadata and controls

71 lines (63 loc) · 1.83 KB

Datatypes

Datatypes are the type of data a variable can store

  • Primitive types
  • Reference types

🧱 Primitive Types

Type description Example
Number Both integers and floating-point numbers (Number literal) 5, 5.55, Infinity, NaN
String Textual data wrapped in quotes (String literal) "Hi", 'Hi', `Hi`
Boolean Logical values: true or false true, false
Undefined A variable that has been declared but not assigned undefined
Null An intentional absence null

Example

let age = 15;
let name = "Rohan";
let isAdult = false;
let Lisence = undefined; // When it is not needed when empty
let favMovie = null; // When it is needed even when empty

🎭 Dynamic typing

JS is a dynamic language i.e., the type of the variable can change during runtime.

let data = 42;      // data is a Number
data = "Forty-two"; // data is now a String
data = true;        // data is now a Boolean

🧩 Reference Types

Type description Example
Object A collection of properties { name: "John", age: 30 }
Array A list of values [1,2,3]
Function A block of code

🔀 Type conversion

Explicitly convert varaible from one datatype to another.
Eg: String -> Number, Boolean -> String

typeof keyword

typeof keyword is used to check the data type of a variable

let data = 10;
console.log(typeof data); //Number

JS has a bunch of built-in ways to convert types. Think of them in 3 buckets: string, number, boolean

Convert to string

String(123) // "123"
(true).toString // "true"

Convert to Number

Number("123") // 123
praseInt("456abc") // 456
**NOTE**
Number("123go") // NaN

Convert to Boolean

Boolean(0) // false
Boolean("Hello") // true

previous

next