Introduction to Variables and Data Types in JavaScript
If you’re new to JavaScript, one of the first concepts you’ll need to learn is variables and data types. Variables act like containers that store values, while data types define the type of data that can be stored in a variable. In this blog post, we’ll provide an overview of variables and data types in JavaScript.
Variables in JavaScript A variable is a named storage location that holds a value. In JavaScript, you can create a variable using the var
, let
, or const
keyword. For example, you can create a variable called name
and assign it a value like this:
let name = "John";
In this example, let
is the keyword used to declare the variable, name
is the name of the variable, and "John"
is the value that is assigned to it. Once you've created a variable, you can use it throughout your code to store and retrieve values.
Data Types in JavaScript JavaScript supports several data types, including:
Primitive data types are immutable meaning not able to be changed and these are the primitive types in JavaScript:
- String: a sequence of characters enclosed in quotation marks
- Number: a numeric value, such as
10
or3.14
- Boolean: a value that is either
true
orfalse
- Undefined: a variable that has been declared but has not been assigned a value
- Null: a variable that has been explicitly assigned the value
null
- Symbol: a new data type introduced in ECMAScript 6, used to create unique identifiers.
Non-primitive type is just opposite of a primitive type meaning it can be changed and there’s only one non-primitive type:
- Object: a complex data type that can store multiple values and properties
Here are a few examples of how you can declare variables with different data types:
let name = "John"; // string
let age = 30; // number
let isMale = true; // boolean
let job; // undefined
let car = null; // null
let id = Symbol("id"); // symbol
let person = { name: "John", age: 30 }; // object
Conclusion :This post covers the basics of variables and data types in JavaScript. Mastering these concepts is essential to writing effective JavaScript code.