Learn JavaScript in 15 Minutes

Learn JavaScript in 15 Minutes was originally published on Springboard.

1. Introduction

1.1 JS in the Console

1.2 JS in a Separate File

2. Basics

2.1 Data Types

2.2 Variables (and Constants)

3. Control Flow

3.1 Boolean Logic

3.1.1 Comparison Operators

3.1.2 Logical Operators

3.2 Conditionals

3.3 Loops

3.3.1 for Loop

3.3.2 while Loop

4. Functions

4.1 Parameters and Arguments

4.2 The return Keyword

4.3 More on Functions

5. Arrays

5.1 Array Methods

5.2 Looping Arrays

5.2.1 for Loop

5.2.2 forEach

6. Objects
7. DOM Manipulation
8. Further Learning

1. Introduction

JavaScript (abbreviated as JS) is a high-level interpreted object-oriented programming language.

When a programming language is described as high-level, it means there is a lot of abstraction. In JavaScript, we don’t have to deal with things like memory management like with low-level languages. JavaScript is scripting language that is interpreted when it’s executed, it doesn’t have to be compiled prior to execution like some other programming languages.

JavaScript conforms to the **ECMAScript** specification.

The ECMAScript specification is used to standardize JavaScript, which is its best-known implementation. You can read more about ECMAScript on this page.

JavaScript is used as a client-side programming language that is executed in the browser (in the frontend). However, nowadays it’s also popularly used in the server-side (backend) via Node.js – which is an engine that allows us to write JavaScript code in the backend web development.

Our browsers display HTML pages with CSS styling, and JavaScript works together with those technologies to add interactivity to the page (using JavaScript, we can make our page dynamic and create things like web applications or games). In other words, it represents a way to add programming logic to our web pages.

These 3 major technologies (HTML, CSS, and JS) combined give us endless possibilities and a lot of power when it comes to web development and web design!

Since JavaScript is the main client-side programming language ran in the browsers, it’s an essential technology to learn as a web developer!

We can use JavaScript to create backend and full-stack web applications using Node.js, we can create mobile applications using frameworks such as Ionic or React Native, or even desktop applications with Electron. It’s also used with extremely popular technologies like React.js.

One of the most popular web browsers is Google Chrome. It has powerful tools that we can utilize while we do web development which includes JavaScript. Make sure that you download and install it on your computer by following this link.

1.1. JS in the Console

To access the JavaScript developer console that allows us to execute JavaScript code and evaluate it directly, open your Google Chrome web browser.

The interactive console is used to quickly execute bits of JavaScript code, understand how it affects your page, test things while developing, etc.

Complete projects and applications based on JavaScript are written and saved in external files that have the .js extension, on the other hand.

We can use the browser console to test how our code works while developing, and then save things and make them persistent in external files.

The Console is a REPL, which stands for Read, Evaluate, Print, and Loop. It reads the JavaScript that you type into it, evaluates your code, prints out the result of your expression, and then loops back to the first step.

To open the console, start Chrome and press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux).

This opens a new tab where we can run JavaScript code. Before learning more details about JS syntax, we are going to get our feet wet by executing a simple line of code:

console.log("Hello, World!"); 

Copy the code above and paste it to the console, then press the Enter key to execute it in the Chrome console. That will print back the message Hello, World! in your console.

1.2. JS in a Separate File

Before proceeding, make sure that you familiarize yourself with HTML and CSS. Check this tutorial learn about those technologies.

If we are not testing how our code works or how our page reacts in the browser console, we want to write JavaScript code in separate files with the .js extension.

To run the JavaScript code written in an external file, we can include it in our HTML documents. That way, when we open the HTML page in the browser, it will also run our JavaScript code that was included in HTML.

To write HTML, CSS or JavaScript code, we want to install a code editor application. Nowadays, one of the most popular tools which allow us to write code is Visual Studio Code. Before writing any code, make sure to download and install it from this link. You can find more information about VS Code in this video tutorial.

To include an external JavaScript file in our HTML document, we use the HTML <script> element with the src attribute which specifies the path to the .js file, as shown in the example below:

  • index.html
  • script.js (located in the same folder)<html> <head> <title>JS Introduction</title> <script src=”script.js”></script> </head> <body> <h1>JS Introduction</h1> </body> </html>console.log(“Hello, World!”);

That will execute the same code that we entered in the Chrome console previously – after we open the index.html file in our browser.

After you open the page, check the Chrome console to see the printed message!

We can also use the <script> element to write code directly between the tags (in the HTML code):

<html> <head> <title>JS Introduction</title> <script> console.log("Hello, World!"); </script> </head> <body> <h1>JS Introduction</h1> </body> </html> 

However, we want to make things more organized, modular, and scalable so the best practice is to write and include external JS files in our HTML.

After setting up our developer tools and getting familiar with what JavaScript is and how we write it, we can finally start learning about the language and the syntax itself!

2. Basics

2.1. Data Types

One of the main ideas for every programming language is the ability to differentiate between categories of data, which vary from language to language. For example, it can differentiate between a number and a word.

In JavaScript, we have the following primitive data types:

  • Number

It represents whole and fractional numbers, and also positive or negative numbers. Here are some examples:

3 8.7 -17 

So, all these fall into the number data type in JavaScript. Some other programming languages will differentiate between whole numbers and fractional numbers, but this is not the case with JavaScript.

We can do math with numbers (make sure to test these by entering them in the Chrome console):

5 + 10 // 15 1/4 // 0.25 // Modulo - remainder operator 10 % 3 // 1 24 % 2 // 0 15 % 11 // 4 

To add code comments which won’t get executed when the code is run, we can write two forward slashes and then the comment text: // this is a comment in JavaScript

  • String

String basically represents text data. Here are some examples:

"Hello World" '100' 

String data is placed inside quotes – that’s what differentiates them from other data types. We can use either single or double quotes to denote strings in JavaScript, as shown in the examples above (but, it’s important to start and end a single string with the same type of quotes).

Even if it has multiple words, "Hello World" is one string. Also, because '100' is inside quotes, it’s a string value that contains digits (therefore, it’s not a number type).

We can join strings using the plus operator:

"hello" + "world" // "helloworld" 

So, JavaScript makes a difference when we use the + operator with strings (concatenates them) versus when we use it with numbers (math addition).

If we want to use quotes inside of strings, we can use backslash \ to escape them:

"He yelled: \"Hello!\"" // We can also use unescaped single quotes inside double quotes and vice versa: "He yelled: 'Hello!'" 'He yelled: "Hello!"' 

Strings also have a length property which shows the number of characters inside of the string. Here is how we can access it:

'hello world'.length // 11 

In addition to that, we can use the following syntax to access individual string characters at a specific index (the count starts from 0):

'hello'[0] // "h" 'hello'[4] // "o" 
  • Boolean

Boolean data type has only two values:

true false 

So, boolean values can either be true or false.

  • null

null is a value that represents a way to express nothingness in JavaScript.

  • undefined

undefined is similar, but it means that something was not yet defined. In other words, that something (a variable) doesn’t have a value yet – check the next lecture dedicated to variables in JavaScript.

  • Symbol

Symbol is a bit more complicated primitive data type, you can check this tutorial to get more information about it – after leaning the JavaScript fundamentals here!

2.2. Variables (and constants)

We use variables to store data in our programs.

A variable is a container that has a name and inside of that container we store some bit of data.

The basic primitive types that we previously covered can be stored in these containers of data (i.e. to variables).

Variables are an important feature of the language – they let us store data and recall it later.

For example, we can have a variable that we save the high score to, if we were creating a game. On a website, we could hold the username of the currently logged in user in a variable.

To create a variable in modern JavaScript, use the let keyword.

The syntax to create (declare) a variable in JavaScript looks like this:

let test; 

The variable is declared but there was no value assigned, therefore it has the undefined value. We can store some data into it by using the assignment operator =:

let test; // declare the variable test = 'Hello'; // Now, it can be to print the string to the console console.log(test); // We can assign a new value to it: test = 'Goodbye'; 

We can combine the variable declaration and assignment into a single line:

let test = 'Hello'; // we are storing the string 'Hello' to a variable named test let randomNumber = 20; let gameOver = true; // To assign a new value: test = 'Goodbye'; // Recall the stored value let firstName = 'John'; console.log('Hello ' + firstName); // 'Hello John' let num = 100; console.log(num + 20 + 5); // 125 

When working with strings, we can also use template strings to embed variable values and other expressions. We surround template strings with the backtick (backquote) “` character, and embed expressions with this syntax: ${expression}.

// Using template strings let firstName = 'John'; console.log(`Hello ${firstName}`); // 'Hello John' 

In older JavaScript code, you may find that the keyword var is used to declare variable instead of let.

var test = "Hello"; 

The var keyword is very similar to the let keyword, but there are some differences which you can later learn about in this video tutorial. It’s important to know that the current/modern approach is to declare variables (containers that can change values) using the let keyword.

Semicolons at the end of the lines, blocks or statements are not mandatory in JavaScript, but it’s a good practice and a convention to always use them when appropriate.

Constants

To declare a constant (which can be looked as a variable which doesn’t change after initially assigning a value), we use the const keyword:

const birthYear = 1983; birthYear = 2000; // results in an error because we it's a constant 

To name variables in JavaScript, the convention is to use camelCase. That means the first letter of a variable name should always be lowercase, and if we have another word we uppercase the first letter of the new word.

3. Control Flow

3.1. Boolean Logic

3.1.1. Comparison Operators

Boolean logic involves writing expressions that evaluated to true or false (boolean values).

A comparison operator compares its operands and returns a logical value based on whether the comparison is true.

Comparison Operators – Assuming num = 5

Equality operators:

  • == (equality check which performs automatic type coercion and compares only values)
  • === (strict equality check where both values and data types have to match)

3.1.2. Logical Operators

Overview – Assuming x = 5 and y = 10

So, with the && (and) operator both sides have to evaluate to true so the whole expression is true. On the other hand, with the || (or) operator one side has to evaluate to true so the whole expression is true. The ! operator will simply reverse the boolean value.

When evaluated in a boolean context, each value can be either truthy or falsy (but not directly equal to the boolean true or false). You can read more in this Stack Overflow answer.

You can read more about operators in JavaScript on this MDN page.

3.2. Conditionals

Conditionals allow us to make decisions in our code – it’s how we add logic to our programming.

In any programming language, there is a need to carry out actions and make decisions depending on different values. Using conditionals allows us to execute different code based on specific values.

The most common conditional statement in JavaScript is the if…else statement:

if (condition) { code to run if condition is true } else if (condition) { code to run if a different condition is true } else { code to run if none of the previous conditions are true } 

The else if block to chain different conditions is optional. We can omit it and just have if and else blocks, and we can also add as many else if statements as we need in between them.

Here is an actual code example:

let age = 18; if (age < 18) { alert("You cannot enter!"); } else { alert("You are old enough to enter."); // this block gets executed } 

You can read more about conditionals in JavaScript on this MDN page.

3.3. Loops

Loops allow us to execute repetitive tasks in our code. In other words, they allow us to execute code repeatedly for a set amount of times (iterations).

For example, if we wanted to print all the numbers from 0 to 99, we can use a loop which will start at 0 and end at 99, which executes the code to print each number in the range. We don’t need to write 100 lines of code where we manually print each number, we can just write a concise loop which does that for us.

3.3.1. for loop

One of the most common loops in JavaScript is the for loop. Its syntax looks like this:

for (initializer; exit-condition; final-expression) { // code to run } 

It starts with the for keyword followed by these items inside the parentheses (separated by semicolons):

  • initializer – usually a number (counter) which is incremented to count how many times the loop has run. It’s commonly named i.
  • exit-condition – a condition which defines when the loop should finish. It gets checked to see if the for loop code should get executed.
  • final-expression – it gets run after each repetition (iteration) of the for loop. We usually increment the initializer/counter to bring it closer to the exit-condition.

Here is a real code example:

for (let i = 0; i < 100; i++) { console.log(i); } 

i++ increments the i variable by 1. It’s equivalent to i = i + 1. Read more on this link.

3.3.2. while loop

There are other types of loops in JavaScript as well, and another important one to know about is the while loop.

It works similarly to the for loop, but it has a slightly different structure. It’s used to repeatedly execute code while a specific condition is true. Here is the syntax:

initializer while (exit-condition) { // code to run final-expression } 

The for loop is usually used when we know how many iterations (repetitions) a loop should have, and we use the while loop if we don’t know.

Here is the same code from the last example, written with a while loop:

let num = 0; while (num < 100) { console.log(num); num++; } 

There is much more to learn about loops in JavaScript! A great place to start reading more about it is this MDN page.

4. Functions

Functions represent an essential concept in programming. They allow us to store a piece of code that does a specific task inside of a defined block and then call that code at a later point, whenever we need to execute that code.

We don’t have to type the same logic over and over again if we need to use it in multiple places in our code. We can store the code that we want to reuse inside of a function, and then call that function throughout our code. Functions are used all the time, and they are one of the building blocks of JavaScript.

Syntax to declare a function in JavaScript looks like this (make sure to test it out in the Chrome console!):

function myFunction() { console.log('Hello, World!'); // we can have many lines of code here // which we can execute at any time by calling the function } // to call the function one time: myFunction(); // call it the second time: myFunction(); 

To execute a function we need to reference its name, directly followed by ().

4.1. Parameters and Arguments

In the previous code example, we learned how to create a function that does the same thing every time.

However, we can make our functions take inputs and produce a different result based on them. When defining a function, we can also define the parameters that it accepts (between the parentheses of the function definition, separated by commas):

function square(num) { console.log(num * num); } 

In the example above, the square function accepts a parameter called num.

When we call square, we need to pass an argument which corresponds to the defined parameter for the function:

square(3); // 9 square(5); // 25 square(10); // 100 

So, the parameter is num and the argument is the number value that we pass when calling the function.

We can make our functions accept as many arguments as needed, for example:

function sum(num1, num2) { console.log(num1 + num2); } sum(100, 50); function greetEveryone(name1, name2, name3, name4) { console.log('Hello, ' + name1); console.log('Hello, ' + name2); console.log('Hello, ' + name3); console.log('Hello, ' + name4); } greetEveryone('Frodo', 'Sam', 'Merry', 'Pippin'); 

4.2. The return Keyword

Every function can return a value after it completes execution. That allows our function to programmatically output a value that we can use in our logic further, assign the function call to a variable, and similar.

To specify a value that our function should output, we use the return keyword (which immediately finishes the function execution when triggered):

function sum(num1, num2) { console.log('This line gets executed.'); return num1 + num2; console.log('The line after the return statement doesn\'t get executed.'); } let calculatedResult = sum(100, 50); console.log('The result is: ' + sum(100, 50)); console.log(sum(100, 50) + 1000); // prints 1150 

Because we defined a return value, we are able to assign the function call to the calculatedResult variable and use it as a value in expressions.

You can find out more about functions in JavaScript on this MDN page.

4.3. More on Functions

Functions can be defined using the following approaches:

Arrow functions

In the newest versions of JavaScript, we can use the arrow function syntax to define our functions, see the examples below:

// standard function declaration function sum(num1, num2) { console.log(num1 + num2); } // function expression const sum = function (num1, num2) { console.log(num1 + num2); }; // arrow function syntax const sum = (num1, num2) => { console.log(num1 + num2); }; 

You can find out more about arrow functions in JavaScript on this page.

5. Arrays

An array represents a list-like object, and it’s another data type in JavaScript. It’s an ordered collection of data. In other words, arrays are used to store multiple values in a single variable. For example, we can store a list of names in an array of values instead of creating a new variable for each name. Arrays can hold any type of JavaScript value.

We can access each value inside the array individually using the index number of the array element (the index starts at 0).

The syntax for arrays in JavaScript looks like this (comma-separated values enclosed in square brackets which denote an array):

const numbers = [1, 2, 3, 4]; const names = ['Frodo', 'Sam', 'Merry', 'Pippin']; // Index: 0 - 'Frodo' // Index: 1 - 'Sam' // Index: 2 - 'Merry' // Index: 3 - 'Pippin' console.log(names[0]); // to access the 1st element of the names array console.log(numbers[3]); // to access the 4th element of the numbers array 

Arrays are a mutable data type, which means that we can modify the elements inside of the array:

const names = ['Frodo', 'Sam', 'Merry', 'Pippin']; names[0] = 'New Name'; // changes the first element of the names array console.log(names); // Similarly to strings, we can use the .length property to find how many elements // are contained in an array (the array length): console.log(names.length); 

5.1. Array Methods

Arrays come with build-in methods that we can use when dealing with this data type. Some of the common ones are:

  • push – used to add an element to the end of an arrayconst colors = [‘red’, ‘blue’, ‘yellow’]; colors.push(‘purple’); console.log(colors); // [‘red’, ‘blue’, ‘yellow’, ‘purple’]
  • pop – removes the last element from an array and returns that elementconst colors = [‘red’, ‘blue’, ‘yellow’]; const removedItem = colors.pop(); console.log(colors); // [‘red’, ‘blue’] console.log(removedItem); // ‘yellow’
  • shift – add to the front of an arrayconst colors = [‘red’, ‘blue’, ‘yellow’];colors.unshift(‘pink’); console.log(colors); // [‘pink’, ‘red’, ‘blue’, ‘yellow’]
  • unshift – remove the first item in an arrayconst colors = [‘red’, ‘blue’, ‘yellow’];colors.shift(); console.log(colors); // [‘blue’, ‘yellow’]

Check out the links to learn about some more array methods here:

And check the list of the available array methods on this MDN page.

5.2. Looping Arrays

5.2.1. for loop

We can use the for loop to iterate over an array. We use the array length property as the condition, so it can loop through all the items in an array:

const names = ['Frodo', 'Sam', 'Merry', 'Pippin']; for (let i = 0; i < names.length; i++) { console.log(names[i]); } 

The following loop will access each array element and print it to the console. The i variable starts at 0 to access the first index and ends at i < names.length because the last element of the array will always be one less than the length of the array (because array index numbers start from 0).

5.2.2. forEach

In JavaScript, we have a built-in method to iterate over each element inside of an array called forEach.

Here is the forEach version of the last example:

const names = ['Frodo', 'Sam', 'Merry', 'Pippin']; names.forEach(function (name) { console.log(name); }); 

We pass a function definition (callback function) as a single argument to the forEach() method, which it automatically calls for each element of the array

You can learn more about how forEach works on this MDN page. Also, there are many more array iteration methodsclick this link to learn more.

6. Objects

Objects are a data type in JavaScript which allows us to store key-value pairs in a single entity.

An object has properties (keys) associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary variables, except for the attachment to objects. The properties of an object define the characteristics of the object.

Instead of using index numbers with arrays, we can use objects to model specific properties to values (objects have no order, unlike arrays which do have order). Here is how the object syntax in JavaScript looks:

const person = { name: 'John', age: 35, city: 'New York' }; 

So, we can store as many pieces of data as we need, and associate each value (on the right) to a property (on the left).

We can access the object properties using the dot notation and the square bracket notation:

console.log(person.age); console.log(person['name']); // To modify object data, we can use the following syntax person.name = 'New Name'; person['age'] = 36; console.log(person); 

We can declare arrays and objects using constants (the const keyword) if we are only modifying the values of an existing array (or key-value pairs of an existing object). Since we are dealing with the same array/object and only changing the inner values (and not changing the variable to point to a new array or object), it has a constant memory reference.

Like arrays, objects can hold any type of data. That means they can hold primitive data types, but also arrays and other nested objects, as well.

Learn more about JavaScript objects on this page.

7. DOM Manipulation

As already mentioned, JavaScript can be used on the pages that we create using HTML and CSS.

After getting comfortable with the fundamentals of JavaScript as a programming language, we can start learning how it can be used to manipulate our web pages – DOM Manipulation.

Using JavaScript on our pages allow us to create games, scrolling effects, dropdown menus, form validations, animations, and many other types of interactivity.

The DOM (Document Object Model) is the interface that allows us to use JavaScript with HTML and CSS. The browser turns every HTML element into a JavaScript object which is stored in the document object that we can access in our JavaScript code.

The basic process is to first select the element that we want to manipulate with JavaScript (we have built-in JS selector methods). For example:

const h1 = document.querySelector('h1'); // selects the h1 element on the page 

Then, we can use different properties that JS makes available on the selected element/object. One of the most popular is the style property where we can use JavaScript to change the CSS styles of the selected element:

h1.style.color = 'purple'; // changes the h1 element color to purple 

Similarly to that, we can change any CSS property of an element on our page.

In addition to that, JavaScript allows us to add event listeners to the page elements, using the addEventListener method. So, we can add a click (or any other event like mouseover, keypress, drag, etc.) event listener which will execute JavaScript code when the user clicks an element (like a button, for example).

const button = document.querySelector('button'); button.addEventListener('click', function () { console.log('You clicked the button!'); }); 

Be sure to create a simple HTML page to try this code out! There is much more to learn about DOM Manipulation and how JavaScript can be used to give superpowers to our page. You can start here:

Also, to learn more about how HTML, CSS and JavaScript works (including how to use them together and manipulate web pages with JavaScript programming), check out this crash course:

8. Further Learning

To master JavaScript and build some exciting projects for your portfolio, check out the following course on Udemy:

Also, to learn more about JavaScript, HTML, CSS and web development in general, check these links:

The post Learn JavaScript in 15 Minutes appeared first on Springboard Blog.

By Kindra Cooper - Springboard
Springboard
Bridging the world's skills gap through affordable, high-quality, online education.