JavaScript Notes

Day 2

JavaScript Notes

Photo by Joan Gamell on Unsplash

Data Types in JavaScript

JavaScript supports various data types that are used to store different kinds of values. Understanding these data types is essential for writing robust code. Let's explore each data type and how to determine the type of a variable using the 'typeof' operator.

Data TypeDescription
NumberRepresents integer or floating point numbers.
StringRepresents a sequence of characters (text).
BooleanRepresents true or false values.
undefinedIndicates that the value is not defined.
nullRepresents the absence of a value or null value.
BigIntIntroduced in ES6, used for large integer values.
SymbolIntroduced in ES6, represents unique and immutable instances.
FunctionRepresents a declared function, including arrow functions.
ObjectRepresents a collection of key-value pairs of different data types.

To find the data type of a variable in JavaScript, we can use the 'typeof' operator, which returns the type of the variable.

var a = 10;
typeof a; //'number'

a = 'Hi';
typeof a; //'string'

a = true;
typeof a; //'boolean'

var b;
typeof b; //'undefined'

a = null;
typeof a; //'object'

a = 12233n;
typeof a; //'bigint'

const sym = Symbol("foo");
typeof sym; //'symbol'

a = () => {console.log('Hi')};
typeof a; //'function'

a = function() {console.log('Hi')};
typeof a; //'function'

a = {key: 'value'};
typeof a; //'object'
a.key; //'value'

a = ['test', 'value'];
typeof a; //'object'
a[0]; //'test'

A function is technically an object, but the 'typeof' operator returns 'function' for functions.

It's important to note that the 'typeof' operator on null also returns 'object.'

Arrays are another data type in JavaScript, and they are of type 'object.'

Arrays and objects share some similarities. In arrays, the keys are numeric values (zero-based index), while objects use string keys to access their elements using the dot notation.

Numbers, Strings, and '+'

The '+' operator behaves differently for numbers and strings. For numbers, it performs addition, while for strings, it concatenates them. Combining strings and numbers results in string concatenation. Remember to use brackets for precise calculations.

String to Number

To convert strings to numbers, JavaScript provides two methods: 'parseInt()' and 'parseFloat()'. 'parseInt()' allows specifying the base as the second parameter, while 'parseFloat()' only accepts one parameter.

Numbers in Different Base Systems

JavaScript allows representing numbers in various number systems by using specific prefixes in their literals. BigInt can be represented in any number system by adding a trailing 'n.'

PrefixNumber System
0 or 0o or 0OOctal
0x or 0XHexadecimal
0b or 0BBinary
No prefixDecimal

String Declarations

In JavaScript, strings can be declared in three ways:

  1. Single Quotes

  2. Double Quotes

  3. Template Literals: These allow for computed values to be inserted within strings using placeholders (${...}).