JavaScript Basics Tutorial
Learn the basics of JavaScript by going through examples you can run directly in the browser! You'll learn the basics required to learn React, Vue or Node.
Watch this tutorial on YouTube! This post contains the same topics, but in a short and easy to read form. Also you might find it handy to copy/paste all the code snippets here used in the video.
What is JavaScript?
JavaScript is a high-level interpreted programming language that's essential in web development. It's used to bring dynamic and interactive features to websites, such as animations and form validations, and also plays a vital role in server programming and mobile app development.
This tutorial covers the basic syntax, the most important parts of the language to make you productive ASAP in frameworks like React, Vue or Node.js.
What are key characteristics of JavaScript?
- High-Level Language: JavaScript, like other high-level languages (PHP, Python, Ruby), offers a more intuitive and human-readable syntax. This makes it easier for developers to express ideas efficiently.
- Interpreted Language: Unlike compiled languages (C, C++, Rust, Fortran), where code is turned into machine code first, JavaScript is executed line by line by an interpreter.
- Isolated from Hardware: Being a high-level language, JavaScript allows developers to write code without worrying about hardware specifics.
Getting Started with JavaScript
To learn JavaScript basics, we'll use the Google Chrome browser and its Developer Tools. That way you most probably have everything you need on your computer.
Opening Chrome Developer Tools
- Open Google Chrome (can be an empty tab).
- Navigate to the View menu, then Developer -> Developer Tools.
- Resize the console for full screen visibility.
- Ensure you're on the 'Console' tab. If not visible, click the chevron icon and select 'Console'.
- Use Ctrl or Command (+/-) to zoom in or out for better visibility.
Variables
Let's talk about variables first. Variables in JavaScript are like containers for storing data values.
How to define a variable?
There are couple of ways to define a variable. These days, you'll mostly use let
if you'd like a mutable variable (variable than can be reassigned) and const
for a variable that can be assigned only once (both actually have a very good use cases!).
- Using
var
:
var
is the traditional way to define a variable in JavaScript. Not used these days (use let
instead).
var name = "John Doe";
console.log(name); // Outputs: John Doe
- Using let and const:
let age = 30;
age = 25; // 'let' allows modification
console.log(age); // Outputs: 25
const country = "USA";
// country = "Germany"; // This would throw an error as 'const' values can't be changed.
Difference between let, const, and var
- let: Allows you to reassign values.
- const: Does not allow reassignment. Ideal for constant values.
- var: The traditional way to declare variables. More details on the differences, especially scope, will be discussed later.
Understanding different data types
JavaScript offers a variety of basic data types, including numbers, strings, booleans, and two types representing empty values: null
and undefined
.
Empty data types: null
and undefined
The difference between undefined
and null
might be a little confusing. You will use use null
if you'd like to say value is explicitly empty. On the other hand, undefined
is the default value of a variable that wasn't initialized. You'd rarely see code setting a value of a variable as undefined
explicity!
- undefined: Indicates a variable has not been assigned a value yet. Example:
let empty; // empty is undefined
- null: Represents an explicitly assigned empty value. Example:
empty = null;
- Comparison:
null
andundefined
are not identical (null !== undefined
).
Numbers in JavaScript
- Can represent integers, negative values, and floating point numbers.
- To check if a variable is of type number, use
typeof
operator. For example, runtypeof 4
in the browser's console, you should receive back the'number'
string.
let age = 30; // typeof age -> 'number'
To check if age
is a number: typeof age === 'number'
(will return true in this case).
Strings in JavaScript
- Represents a sequence of characters.
- Can be enclosed in single or double quotes (no difference in JavaScript). Example:
let greeting = "Hello";
Booleans in JavaScript
- Represents logical values:
true
orfalse
. - Note: JavaScript treats
0
asfalse
and1
astrue
. - Use strict equality for accurate comparison (e.g.,
0 === false
isfalse
).
What's type coercion?
Type coercion in JavaScript is the automatic conversion of values from one type to another.
- Can lead to unexpected results. Example:
1 + "2"
results in"12"
, not3
. - Use strict equality operator (
===
) instead of equality (==
) to avoid type coercion.
Numeric precision
JavaScript may have precision issues with decimal numbers. It's actually a common problem. For example: 0.1 + 0.2 !== 0.3
. It might come as a shock at first. To compare these decimal numbers, you need to use (0.1 + 0.2).toFixed(2) === (0.3).toFixed(2)
.
In the browser console, just type: (0.1+0.2)
. You'd see why this is not equal to 0.3
. You should see 0.30000000000000004
.
Functions in JavaScript
Functions are blocks of code designed to perform a specific task and can be executed when called.
Defining functions
Use the function
keyword, followed by a name, parameters and a body. Example:
function sum(a, b) {
return a + b;
}
const result = sum(2, 4); // result is 6
Functions as first-class citizens
Functions being First-Class Citizens means functions can be stored in variables, passed as arguments, or returned from other functions. Example:
let x = sum;
console.log(x(5, 4)); // Outputs: 9
Introduction to arrays
Arrays are data structures that can hold multiple values.
Creating and accessing arrays
- Defined using square brackets [].
- Access elements using an index (starts at 0).
let numbers = [1, 2, 3, 4, 5];
console.log(numbers[0]); // Outputs: 1
How to get the array length?
Use .length
property to find the number of elements in an array. Example:
numbers.length; // Outputs: 5
Understanding objects in JavaScript
Objects in JavaScript are collections of key-value pairs, where each key is unique.
How to create objects?
Define objects using curly braces {}
. Example:
let person = {
name: "John Doe",
age: 30,
country: "USA",
};
Access properties using dot notation or square brackets.
person.name; // 'John Doe'
person["age"]; // 30
Square brackets notation is useful when a property name is not a valid identifier, eg. max-age
. You can't write person.max-age
, it'll cause the syntax error. In this case you'd need to use person['max-age']
.
How to modify objects?
- Add new properties:
person.email = 'john@example.com';
- Delete properties:
delete person.email;
Methods in objects
- Methods are properties that are functions. Example:
let example = {
sayHello: function () {
console.log("Hello");
},
};
example.sayHello(); // Outputs: 'Hello'
Control structures in JavaScript
Control structures in JavaScript allow you to control the flow of your program.
If statements
- Run code based on a condition.
- Example:
function hasPassed(score) {
if (score >= 50) {
console.log("Passed");
} else {
console.log("Failed");
}
}
hasPassed(51); // Outputs: 'Passed'
For loops
- Execute a block of code a specific number of times.
- Commonly used for iterating over arrays.
- Example:
let letters = ["a", "b", "c", "d", "e"];
for (let i = 0; i < letters.length; i++) {
console.log(letters[i]);
}
// Outputs each letter from the array
Variable scope in JavaScript
Var, let, and const
var
: Function scope, accessible within the function it is defined in, including nested blocks.let
andconst
: Block scope, only accessible within the block{}
they are defined in.
Examples:
- Var Scope:
function example() {
var v = 5;
if (true) {
var v = 10;
console.log(v); // 10
}
console.log(v); // 10
}
- Let Scope:
function example2() {
let l = 5;
if (true) {
let l = 10;
console.log(l); // 10
}
console.log(l); // 5
}
Manipulating JavaScript arrays
Adding and removing elements
- pop(): Removes the last element.
- push(): Adds an element to the end.
- shift(): Removes the first element.
- unshift(): Adds an element to the start.
Examples
- Pop and Push:
let x = [1, 2, 3];
x.pop(); // Removes 3
x.push(4); // Adds 4
- Shift and Unshift:
x.shift(); // Removes 1
x.unshift(0); // Adds 0 at the start
The spread operator
- Creates a new array by spreading an existing array.
- Example:
let y = ["b", "c", 3, "a"];
let f = ["a", ...y, 5]; // ['a', 'b', 'c', 3, 'a', 5]
JavaScript objects
Object.keys() and Object.values()
- Object.keys(): Returns an array of a given object's property names.
- Object.values(): Returns an array of a given object's own enumerable property values.
Examples
- Iterating over Object Properties:
let person = { name: "John", age: 30, country: "USA" };
for (const key of Object.keys(person)) {
console.log(`The value of ${key} is ${person[key]}`);
}
- Calculating Average from Object Values:
let students = { "John Doe": 45, "Jane Doe": 67 };
let sum = Object.values(students).reduce((acc, score) => acc + score, 0);
let average = sum / Object.values(students).length;
console.log(average); // 56
Arrow functions in JavaScript
- Shorter syntax for writing functions.
- If only one expression, implicit return.
- If multiple expressions, use
{}
andreturn
keyword.
Examples
- Single Expression Arrow Function:
const square = (x) => x * x;
console.log(square(4)); // 16
- Multiple Expressions Arrow Function:
const square2 = (x) => {
console.log(`Input was ${x}`);
return x * x;
};
console.log(square2(4)); // Input was 4, 16
Array filter method
The filter
method in arrays allows you to create a new array containing only elements that meet certain criteria.
Example: filtering even numbers
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter((x) => x % 2 === 0);
console.log(evenNumbers); // Outputs: [2, 4]
The filter
method does not modify the original array but instead creates a new one based on the provided condition.
Example: filtering people by age
let people = [
{ name: "Pyotr", age: 35 },
{ name: "John", age: 40 },
];
let peopleUnder40 = people.filter((person) => person.age < 40);
console.log(peopleUnder40); // Outputs: [{ name: 'Pyotr', age: 35 }]
Array map method
The map
method creates a new array by transforming every element in the original array individually.
Example: doubling numbers
let doubledNumbers = numbers.map((x) => x * 2);
console.log(doubledNumbers); // Outputs: [2, 4, 6, 8, 10]
Example: extracting ages
let ages = people.map((person) => person.age);
console.log(ages); // Outputs: [35, 40]
Array reduce method
The reduce
method reduces an array to a single value by applying a function to each element and accumulating the results.
Example: calculating average age
let totalAge = ages.reduce((accumulator, age) => accumulator + age, 0);
let averageAge = totalAge / ages.length;
console.log(averageAge); // Outputs the average age
Simplified average calculation
let average =
people.map((person) => person.age).reduce((accumulator, age) => accumulator + age, 0) /
people.length;
console.log(average); // Outputs the average age directly
These array methods are powerful tools for processing and manipulating data in JavaScript, providing efficient ways to handle collections of data.