Gabriel Cseh

Understanding JavaScript Data Types

JavaScript is a dynamically typed language, which means variables can hold values of any data type without any type declaration. This flexibility makes it essential to understand the various data types in JavaScript and how they work.

Primitive Data Types

JavaScript has six primitive data types:

1. String

A sequence of characters used to represent text. Strings can be created using single, double, or backticks quotes.

let name = 'John';
let greeting = "Hello, World!";
let template = `My name is ${name}`;

2. Number

Represents both integer and floating-point numbers. JavaScript does not differentiate between the two.

let age = 30;
let price = 19.99;

3. Boolean

Represents a logical entity and can have only two values: true or false.

let isAvailable = true;
let isCompleted = false;

4. Null

Represents the intentional absence of any object value. It is one of JavaScript's primitive values.

let result = null;

5. Undefined

A variable that has been declared but has not yet been assigned a value.

let x;
console.log(x); 
// undefined

6. Symbol

A unique and immutable primitive value and may be used as the key of an object property.

let sym = Symbol('description');

Non-Primitive Data Type

1. Object

Objects are collections of key-value pairs. Keys are strings (or Symbols) and values can be of any type.

let person = {
  name: 'John',
  age: 30,
  isEmployed: true
};

2. Array

Arrays are a special type of object used for storing ordered collections of values.

let numbers = [1, 2, 3, 4, 5];

Type Checking

Use the typeof operator to check the type of a variable.

// string
console.log(typeof 'Hello'); 
// number
console.log(typeof 42); 
// boolean
console.log(typeof true); 
// undefined
console.log(typeof undefined); 
// object
console.log(typeof { name: 'John' }); 
// object
console.log(typeof [1, 2, 3]); 

Conclusion

Understanding JavaScript data types is fundamental for writing robust and error-free code. Remember that JavaScript is dynamically typed, so the type of a variable can change during the execution of the program. Always use the appropriate data type for your variables and leverage the typeof operator for type checking.

Happy coding!

Explanation:

  • Primitive Data Types: Detailed explanations and examples for string, number, boolean, null, undefined, and symbol.
  • Non-Primitive Data Type: Examples of objects and arrays.
  • Type Checking: Demonstrates how to use the typeof operator to check the type of variables.
  • Code Blocks: Simplified using standard Markdown code blocks for easier use and readability.