Like any other programming language, knowing the basic concepts of a language will help your understanding and usage of the language. In this article, we'll be learning about some of the basic concepts you need to know when writing JavaScript.
How to start writing JavaScript?
You can write JavaScript code directly in your browser, if you are using a windows/Linux operating system, open your console by clicking ctrl + shift + j
, on macOS simply click Option + ⌘ + J
, This will open up your browser console where you can start writing some basic JavaScript code.
You can also use a script tag inside your HTML file to write your JavaScript code or you can create a different file for your code and link it via the script tag.
Writing JavaScript inside your script tag:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
</head>
<body>
<script>
// you can write your JavaScript code within this script tag
let name = prompt('what is your name?');
alert(name);
</script>
</body>
</html>
Linking your external JavaScript file:
To do this, create a file that ends with the .js
extension and link it via the script tag. Example, you have a file named script.js
in the same directory(folder) with your HTML file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>
The src attribute specifies the url of the external file.
Now that we've seen how to get started with writing JavaScript code, let's look at some of its fundamental concepts.
STATEMENTS
A statement is an instruction, it tells the computer what to do. Any piece of code that returns a value is a statement. Below is an example of what a statement looks like in JavaScript:
2 + 2; // → 4
40 - 2; // → 38
console.log("hello world") // → "hello world"
COMMENTS
comments are used to add descriptions to our code, it helps us understand what action a particular line of code is performing. Anything written in a comment block would be ignored by the interpreter(meaning it won't be executed). Comments can be written on one line or it can span across multiple lines (this is called a multi line comment).
VARIABLE
Variables helps us to clearly understand our code by labelling the data's that we have in our program. Think of variable as a container that stores value, this value can then later be used in our code by referencing that variable name. There are some certain rules to follow when creating variables.
Naming conventions
When naming your variable's in JavaScript, the following rules should be followed:
- The name must contain only letters, digits, or the symbols $ and _.
- The first character must not be a digit.
- Variables are case sensitive
let name; and let NAME
are not the same. - Always name your variables in a clean, obvious and human readable format, a variable should describe clearly the data it holds, doing this will keep your code clean.
- Do not use hyphens to separate between two or multiple words.
let first-name; // → this is wrong
let first_name; // → this is correct
To create a variable, we use the let or const keyword.
let username1 = "Moses"; // → using let keyword
const username2 = "jacob"; // → using const keyword
What's the difference?
- Using const to create a variable will define a constant reference to the value that the variable holds, variables created using const cannot be reassigned. For example, you cannot do this:
This will throw an error:
TypeError: Assignment to constant variable...
but this is possible using let:
- Variables created using let can be declared first and be initialized later.
while const variables must be initialized during declaration
const a = 40; // → variable is declared and initialized.
Not declaring and initializing const variable at once will result in an error.
this returns an errorUncaught SyntaxError: Missing initializer in const declaration
- You can also declare multiple variable at once in the same statement, just as in the code below:
NB: Variables created using let and const cannot be redeclared. You cannot declare the same variable more than once.
VAR
Variable's can also be created using the var keyword, however this should be avoided as it can cause some weird behaviour in your code especially if you are not familiar with it. The normal way of creating a variable is using let and const, you can read more about using the var keyword here.
DATA TYPES
Data type is the classification of the different types of data which we can use within our code. In programming, each value is of a particular type and each data type has some set of operations that could be applied to it. While some of this operations are unique to a data type, some operations can be carried out on more data one data type. For example the addition operation can be performed on both a string and a number data type, although they behave differently, below are some of the most basic data types in JavaScript:
STRING
A string is a value or collection of values wrapped inside of a quote. You can use a single quote(' '), double quote(" ") or backticks to create a string.
let str1 = "hello"; // → Double quote
let str2 = 'hello'; // → single quote
let str3 = `hello`; // → backtick
NB: Using the same kind of quote within a string would result in an error. You cannot do this:
let sentence = "This is "superb"";
returns an Error: Uncaught SyntaxError: Unexpected string
but using a different kind of quote will work. Eg, using a double quote inside a single quoted string:
let sentence = 'This is "superb"'; // or
let sentence = `This is "superb"`;
Number
Number represents an integer or a floating point number, the number type as the name suggests only contain numbers, string cannot be added to it.
let number = 12345; // → correct
let number = 123452abcd; // → incorrect
BigInt
In JavaScript, the Number type has some certain limitations. Integers greater than 9007199254740991 (2*53 -1) or less than -9007199254740991 (-(2*53 -1)) for negatives, cannot be represented using the Number type. BigInt allows us to represent integers that cannot be represented by the number type. we create a BigInt by appending "n" to the end of a number or Using the BigInt constructor to wrap the values. Example:
/* Here num loses its precision because its value is the greater
than the maximum number JavaScript can represent(2**53 -1).
*/
let num = 9999999999999999;
console.log(num); // → 10000000000000000
To solve this, wrap the number in a BigInt constructor or append n to the number.
let bigInt = 9999999999999999n; // → 9999999999999999
let bigInt1 = BigInt(9999999999999999); // → 9999999999999999
Boolean
A Boolean contains only two values, true or false. we use a Boolean to represent a state/condition. It acts like a switch, it can either be On or Off. Booleans can be gotten as a result of comparisons, for Example:
let isLessThan = 1 < 100; // → returns `true`
let isGreaterThan = 1 > 100; // → returns `false`
you can also directly assign a Boolean value to a variable.
let itemExist = True;
Null and Undefined
Null means empty or value unknown, we use null when we want to indicate that the value of a variable is unknown. Example:
let name = null;
Undefined
While we assign a null value to indicate absence of a value, JavaScript uses Undefined as its default way of letting us know that a variable is not yet assigned a value. For example, when you try to access a variable that is declared but not assigned a value, it returns undefined
let name;
console.log(name); // → returns undefined
Technically, you can also assign an undefined value to a variable, but it is not recommended as that's the reserved/default way the language to indicate the absence of a value. Use null to indicate that a variable's value is not yet known.
OBJECTS
Object is a special type in JavaScript, all other types are called primitive types because they can only be of a single data type, either a string, Boolean or number but it cannot contain both at the same time. Objects allows us to store more than a single value at a time and the value can be of any type. Below is an example of an object containing more than one data type.
let obj = {
name: "moses",
tel: 123456,
Boolean: false,
arr: [1,2,3,"name", true, false]
}
The above object contains a string, number, Boolean, and array(this is a special type of object).
To access a value in an object, we call the object name followed by .
then the key that holds the value.
obj.name // → 'moses'
obj.tel // → 123456
obj.arr // → [1,2,3,"name", true, false]
NB: To check the data type of a value, use the typeof operator.
typeof "name" // → String
typeof 123 ; // → Number
typeof true; // → Boolean
The above are some of the most common data type you'll come across when writing JavaScript.
LOOPS
We use loops when we want to run a piece of code repeatedly. The three basic kind of loops are: For loop
, While loop
and the Do While
loop.
For Loop
The for loop has the following syntax:
for(statement; condition; increment/decrement) {
// loop body or code to be executed
}
The statement is executed once before the loop starts running
If the condition returns true, the loop body will be executed
again, if false the loop ends.Increment/decrement occurs each time the loop body executes,
without it the loop will execute forever or until our browser
crashes(this is called infinite loop)
Example code:
let's say you have a piece of code that you want to run three times
let user1 = "anonymous";
alert(user1);
alert(user1);
alert(user1);
// this above alerts "anonymous" three times in your browser
instead of repeating the same code, you can use a for loop to achieve the same result:
let user1 = "anonymous";
for(let i=0; i < 3; i++) {
alert(user1);
}
While Loop
The while loop has the following syntax:
while(condition) {
// loop body or code to be executed
}
- if the condition returns true, the loop body will continue to be executed. You might wondering, won't that cause an infinite loop?. Yes, that's why it's important to set a stop condition inside the loop body.
let i = 0;
let name = "anonymous";
while(i < 5) {
alert(name);
i++ // this is the same as doing i+=1
}
do while Loop
While the code inside the body of a while loop runs as long as the condition returns true, the do while runs the loop body once before checking the condition, if true, it runs again else the loop ends. The do while loop has the following syntax
do {
// loop body
} while(condition )
Example code:
let i = 0
do {
alert(i)
i++
} while(i < 5)
In the above code, the loop body will run once before checking the condition, if it return false then the loop ends. Use a do while loop in cases where you need to run some code at least once regardless of your condition.
NB: it is important to set a stop condition on a loop to avoid creating an infinite loop.
Top comments (0)