Hello and welcome!! 🤩🤩🤩
Today we will be starting our Javascript class.
Javascript is a vast topic. Javascript has been adapted to various aspects of technology and programming, including AI, web development, and others.
In this tutorial, I will explain some important key concepts to note as you go on your Javascript journey. However, some concepts I will be demonstrating with a solved example.
Table of Contents
1. Introduction
2. Javascript Keywords
3. Variable declaration
4. Data types in Javascript
5. Naming conventions in javascript
6. Scope in Javascript
7. Javascript blocks
7.1. Functions
7.3. Loops in Javascript
8. What is 'this'?
9. Data types cont'd
9.4. Arrays in Javascript
9.5. Objects in Javascript
10. Methods in Javascript
10.6. String methods
10.7. Array Methods
11. Array and object destructuring in Javascript
12. Functions and types of functions
12.8. Function return statement in JavaScript
12.9. Arrow functions
13. Javascript Spread operator
14. References
Introduction
👉🏾 Javascript is the world's most popular programming language.
👉🏾 Javascript is the programming language of the Web.
👉🏾 JavaScript is easy to learn. 😏
Javascript Keywords
In computer programming, keywords are predefined words in a programming language with a specific use. Additionally, we use them to define the structure and flow of a program. Furthermore, they specify the operations that the program should perform.
In javascript, there are keywords like const
, var
, catch
, await
, typeOf
, static
, protected
, goTo
, let
amongst others.
Variable declaration
Think of a variable as an empty container in which you want to store a product. Let me paint a scenario: you are moving out of your house, and have gathered a lot of moving boxes to contain your belongings. You start in the living room, pick up a box, label it "living room", and put all the living room items in it. You continue this process until you get to the garage. The boxes are variables, meaning they can contain any information or data. The labeling is called a variable name, and the items inside the box are the data stored in the variable.
x = 'I am a stranger in this land.'
In the above example; we see that x
is the variable name, I am a stranger in this land
is the information we are storing in a box x
(which is our variable). =
is a connector. Its function is to connect a variable name with the data to be stored in the variable.
Data types in Javascript
Data types define the various forms of data that we will be working with and storing in variables. There are five basic, or primitive, forms of data in Javascript. Strings
, integers
, booleans
, undefined
, and null
are the five most fundamental forms of data. These are known as primitive data types. A single variable can only hold one kind of data.
Let's go over each type of data and what it can be used for in more detail.
Strings are collections of alphanumeric and symbol characters. This is how we'll save letters and words, such as addresses.
Numbers are exactly how they sound. They are numbers, including integers and decimals. Numbers are frequently used by computers to execute mathematical operations, but they can also simply be a number, such as the number of ice cream flavors available at a given establishment.
Booleans can only have two possible values. Both true and false. They represent any data that has only two states, such as a light switch. Either on or off.
The undefined data type indicates that the variable was created but never assigned a value. It is nothing because no one has bothered to tell it what it should be worth.
Null is similar to undefined in that it must be explicitly set. It also implies emptyness or nothingness, but it's because a developer commanded it to be that way.
Naming conventions in javascript
When working in an organization, as a team, or individually, certain principles have to be followed or adhered to. This can vary depending on individual, team, or company standards.
Variable names should have meaning, representing what data they are holding or where they are to be used.
Variable names in JavaScript are conventionally written using the camelCase method. In the case of a compound word name, the first letter of the second word should be capitalized, while the others are in small letters.
End every piece of code or code block with a semicolon
;
. Unlike in other languages with strict syntax rules, when writing Javascript code, semicolons are not added, it doesn't break the flow of the code. However, it is important to add these semicolons for readability.
You can find more Javascript conventions here.
Scope in Javascript
Scope determines the accessibility (visibility) of variables. JavaScript has 3 types of scope:
Block scope
Function scope
Global scope
Block scope: Before ES6 (2015), JavaScript had only Global Scope and Function Scope. ES6 introduced two important new JavaScript keywords: let
and const
. These two keywords provide Block Scope in JavaScript. Variables declared inside a { }
block cannot be accessed from outside the block.
{
let x = 2;
}
// x can NOT be used here
Function scope: JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var
, let
and const
are quite similar when declared inside a function.
function functionExample() {
var variableName = "Volvo"; // Function Scope
};
Global scope: Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var
, let
and const
are quite similar when declared outside a block.
let x = 2; // Global scope
Javascript blocks
Functions
A function is a block of reusable code written to perform a specific task. You can think of a function as a sub-program within the main program. A function consists of a set of statements
but executes as a single unit. A function can be written like:
function sayHello() {
console.log("Hello world");
};
// sayHello()
The code block above is the common syntax for writing a function in javascript. There is present the function
keyword. The name of the function is followed by parentheses which can include parameters or be left blank, and a set of curly braces that encloses the entire function block. A set of instructions or arguments that are supposed to run once the function is called.
Outside the function scope, we see, sayHello()
this is a function call. Meaning, we are telling our computer to execute the commands within the function block.
function addNumbers(num1, num2) {
console.log(num1 +num2)
};
addNumbers(1, 2);
The above is an example of a function with parameters. A function can contain many parameters, of various data types.
Conditional statements
If/Else statements: Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In Javascript, we have the following conditional statements:
Use
if
to specify a block of code to be executed, if a specified condition is trueUse
else
to specify a block of code to be executed, if the same condition is false-
Use
else if
to specify a new condition to test, if the first condition is false.
var hour = 24 if (hour < 18) { greeting = "Good day";} else if (hour = 12) { greeting = "It is noon!" } else { greeting = "Good evening"; } console.log(greeting)
In the example above, we are telling the computer to give an output such that (
if
) the value ofhour
is <18, it should log on the console "Good day". However (else if
), if the value ofhour
=12, it should log on the console, "It is noon!". Then (else
), if the value ofhour
is >18, it should log on the console "Good evening".
Switch statements: Switch statements are an upgrade to the if/else statement. The switch
statement specifies many alternative blocks of code to be executed.
var testScore = prompt("What is your score?");
function grade(testScore) {
switch (true) {
case testScore <= 39:
alert("You got an F!");
break;
case testScore <=44:
alert("You got a E!");
break;
case testScore <= 49:
alert("You got a D!");
break;
case testScore <= 59:
alert("You got a C!");
break;
case testScore <= 69:
alert("You got a B!");
break;
case testScore <= 100:
alert("You got an A!");
break;
default:
alert("You did not take the test!");
break;
}
}
grade(testScore);
Above, we have a function that takes a switch
statement. We initially created a variable to store a user's input. We take the value of that input and analyze it with our switch
statement such that if it is less than or equal to (<=
) the number specified in either of our cases, the command inside the case
block will be run. Think of each case as an else if
statement.
Loops in Javascript
Loops can execute a block of code as long as a specified condition is true.
-
While loops: The
while
loop loops through a block of code as long as a specified condition is true.
while (i < 10) { text += "The number is " + i; i++; }
In the above example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10.
-
While..Do loop: The
do...while
statements combo defines a code block to be executed once, and repeated as long as a condition istrue
. Thedo...while
is used when you want to run a code block at least one time.If you use a variable in the condition, you must initialize it before the loop, and increment it within the loop. Otherwise, the loop will never end. This will crash your browser. If the condition is always true, the loop will never end. This will also crash your browser.
let text = "Hello"; let i = 0; do { text + "John"; i++; } while (i < 5);
Execute a code block
text + "John"
once, and then continue if condition (i < 5) is true. -
For loops: The
for
statement defines a code block that is executed as long as a condition istrue
.for (statement 1; statement 2; statement 3) { code block to be executed }
- Statement 1: command to be executed before the code block starts. (Optional). This parameter can be omitted, but not the semicolon ";"
- Statement 2: The condition for running the code block.
If it returns
true
the loop will start over again; otherwise, the loop will end. This parameter can be omitted, but not the semicolon ";" - Statement 3: command to be executed after the code block. This parameter can be omitted, but not the semicolon ";"
If you omit statement 2, you must provide a break inside the loop.
Otherwise, the loop will never end. This will crash your browser.
What is 'this'?
In JavaScript, the this
keyword refers to an object.
Which object depends on how this
is being invoked (used or called).
The this
keyword refers to different objects depending on how it is used:
In an object method, |
Alone, |
In a function, |
In a function, in strict mode, |
In an event, |
Data types cont'd
Arrays in Javascript
In JavaScript, an array is an ordered list of values. Each value in an array is called an element and is identified by an index. An array can hold values of mixed types. For example, you can have an array that stores elements with the types number, string, boolean, and null.
var anArray = ["hello", 1, null, false];
The above is the more common way of writing out an array in Javascript.
However, there is another way: using the Array
constructor function.
var emptyArray = new Array();
var controlledArray = new Array(6);
var anArray = new Array(1, 'hello', null, false];
The example above has three examples using the Array constructor function
. In the first line, what we have done is initialize an empty array. That is, we have opened up a 'box' or 'container' in which to store our data. This creates flexibility in that it allows our array to take any number of data inputs. In the second line, we have a controlled array. A controlled array in that we have specified a total number of values that the array is allowed to store or carry. In this case, we have made it so that controlledArray
can only have six values. In the last line, we have initialized an array, as we did in the first code example above.
A way to initialize an empty array is
var emptyArray = []
As earlier stated, values in a Javascript array are identified by their index. In programming, we start our indexing from 0, not 1.
var array = [1,2,3,4,5];
Accessing values
From array
above, our value '1' is indexed at 0. Subsequently, '2' is indexed at 1, and so on. This is a concept new programmers often struggle with (I know I did 😅), but in time and with frequent practice, it becomes second nature knowledge to you.
Note: When we start indexing from reverse, that is, from the end of a value to the beginning, we start our index from -1. That is, from the example above, in reverse counting, the index of '5' is -1.
To pick off a value in an array by its index, we use the following syntax:
var array = [1, 2, 3, 4, 5, 6];
console.log(array[1], array[4], array[0]);
//console output: 2, 5, 1
Objects in Javascript
An object in JavaScript is an unordered collection of key-value pairs. Each key-value pair is referred to as a property. A property's key can be a string. A property's value can be anything, such as a string, a number, an array, or even a function. There are numerous ways to construct an object with JavaScript. The object literal notation is the most often used.
var objectExample =
{name: 'John',
num: 15754,
isEducated: false,
runOnce() {return 'I ran once!'}
};
Accessing properties:
To access a property of an object, you use one of two notations: the dot notation
and array notation
.
var objectExample =
{name: 'John',
num: 15754,
isEducated: false,
runOnce() {return 'I ran once!'}
};
console.log(objectExample.num) //this is the dot notation
console.log(objectExample['isEducated']); //this is the array notation
/*
console output:
objectExample.num: 15754
objectExample['isEducated']: false
*/
Methods in Javascript
An object is a collection of key/value pairs or properties.
There are a lot of JavaScript methods that are useful to our progress in JavaScript development. I will only touch on two in this article. However, you can read about more Javascript methods and how you can use them here.
String methods
String methods are methods that we can use on strings to either modify them or read their values.
String length: This is a string property that tells us the number of characters contained in a string.
var string = 'string';
var length = string.length;
console.log(length);
//console output: 6
Properties or methods are attached after a dot notation
at the end of our variable name. In the above code block, we see that the length
property was attached with a dot notation
at the end of our variable name string
.
String extraction
There are 3 methods for extracting a part of a string:
slice(start, end)
: this specifies to extract a string from the start of an index to the end of the index.substring(start, end)
: in this method, any negative index is treated as starting from index zero.substr(start, length)
: in this method, the second parameter is used to specify the length(or extent) to which we want the string extracted.
var text = 'This is a full text.';
var slice = text.slice(5, 11);
var substring = text.substring(-5, 11);
var substr = text.substr(5, 11);
console.log(slice, substring, substr);
/* console output:
slice: is a f
substring: This is a f
substr: is a full t
*/
In the code block above, we see that with .slice
, we got the string sliced from index 5 to index 11. But we see something funny here. The extraction does stop at 10. Yes, that is because in programming, when selecting a range, we start from the beginning of the range to the number just before the end of the range. So, as in the example above, our extraction stopped at index 10.
Please note that in a string such as the one we have above, whitespaces are indexed as well.
Converting to upper and lower cases
A string is converted to uppercase with toUpperCase()
A string is converted to lowercase with toLowerCase()
var example1 = 'hello';
var upperCase = example1.toUpperCase();
var example2 = 'HELLO';
var lowerCase = example2.toLowerCase();
console.log(upperCase, lowerCase);
/*
console output:
upperCase: HELLO
lowerCase: hello
*/
For more string methods, and the beautiful things we can do with them, check out W3School's documentation on string methods.
Array Methods
Array Length
The array length property serves the same purpose as the string length property in that it is used to tell the length of an array.
var array = ['hello', 1, null, false];
console.log(array.length);
// console output: 4
Popping and Pushing
When you work with arrays, it is easy to remove elements and add new ones.
This is what popping and pushing are: Popping items out of an array, or pushing items into an array.
var salutations = ['Hello', 'Hi', 'Hey', 'Howdy']
salutations.pop();
console.log(salutations);
salutations.push('Ekaroo');
console.log(salutations);
/*
console output:
salutations.pop(): ['Hello', 'Hi', 'Hey']
salutations.push('ekaroo'): ['Hello', 'Hi', 'Hey', 'Ekaroo']
*/
For more on array methods, and the beautiful things we can do with them, check out W3School's documentation on array methods. Also, check out this amazing article on JavaScript array methods.
Array and object destructuring in Javascript
The destructuring assignment is a cool feature that came along with ES6. Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables.
let array = [1, 2, 'kitty', 4, 5, 6, 7];
let [1, 2, 3, 4, 5, 6, 7] = array;
console.log(3);
//console output: kitty
This might seem as though we almost reversed our array. What we did was assign a variable name to each item/value in our array, to make it easy for retrieval. Instead of typing array[3]
to get the item at index 3
, all we had to do was type in '3'. You can read more about destructuring here.
Functions and types of functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
Get a better introduction to functions in Javascript from our lesson last week.
Broadly speaking, JavaScript has four kinds of functions:
- Regular function: can return anything; always runs to completion after invocation
The general syntax for a JavaScript function is
function thisIsAFunction() {
//Enter function code block here
}
Generator function: returns a
Generator
object; can be paused and resumed with theyield
operatorAsync function: returns a
Promise
; can be paused and resumed with theawait
operator.
The general syntax for a JavaScript async function is
async function thisIsAFunction() {
//Enter function code block here
}
-
Async generator function: returns an
AsyncGenerator
object; both theawait
andyield
operators can be used
Function return statement in JavaScript
When JavaScript reaches a return
statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller".
function myFunction(a, b) {
return a * b;
// Function returns the product of a and b
}
console.log(myFunction(5, 6));
//console output: 30
Arrow functions
An arrow function expression (also called a fat arrow to distinguish it from a hypothetical ->
syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its own this
. Arrow functions are always anonymous.
Two factors influenced the introduction of arrow functions: shorter functions and the non-binding of this
.
const arrow = () => {return 'Her name is Chloe'}
arrow()
The above is a standard syntax for an arrow function. Arrow functions are very effective for writing in-line functions or for returning only one value.
function fizzBuzz() {
for (let i = 0; i < 100; i++) {
if (i % 15 === 0) {
console.log("fizzBuzz")
}
else if (i % 3 === 0) {
console.log("fizz")
}
else if (i % 5 === 0) {
console.log("Buzz")
}
else {
console.log(i)
}
}
}
fizzBuzz()
The above code block is an example of a function solving the famous Fizzbuzz algorithm challenge. I detail more about this solution here.
Javascript Spread operator
This is my favorite thing about ES6! 🤣
The JavaScript spread operator (...
) allows us to quickly copy all or part of an existing array or object into another array or object.
var firstSixNumbers = [1, 2, 3, 4, 5, 6];
var firstTenNumbers = [...firstSixNumbers, 7, 8, 9, 10];
console.log(firstTenNumbers);
//console output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
We see above how we did not have to copy all the values from our first array into the second one. We simply had to spread it in the second one. Imagine how useful this will be for an array with a longer length or more!
Top comments (6)
It can also be a
symbol
.Yes, I recently came across this. Thank you so much for mentioning it.
Well-documented article!
Thank you so much!
Insightful article
Thank you!