Web Dev Bootcamp ∙ Learn Javascript part 1 ∙ Basics
Hieu Nguyen · May 03, 2020 · 13 min read
0
0 leave some love!
What is Javascript
Javascript is an interpreted language built for the web. Interpreted here means that there is no compilation of the code into binary before it is executed.
You can try this out by opening a browser, and then opening up the console. For google chrome, you can use fn12
to open the developer tool bar
Why Learn Javascript
- It is very easy to learn
- most of the web runs javascript as the main scripting language to make website more interactive
- You can write Javascript on the frontend and the backend using NodeJS
- If you want to become a web developer, Javascript is standard knowledge.
- There are a lot of popular frameworks and libraries (React) that uses Javascript
Goal
The goal is to cover the basic of Javascript, especially the skills you need to be successful when doing frontend work in React and backend work with NodeJS
Hence, we will not cover everything there is to know about Javascript (which is quite a bit). However, feel free to do personal research and learn more about it at your own leisure.
Getting Started
Creating a Javascript file is super easy. Let’s create a new folder for this session
mkdir learn-Javascript
Let’s navigate into the folder
cd learn-Javascript
Create two files index.html
and index.js
. Note: the Javascript file ends with a .js
touch index.js index.html
Now let’s write some Javascript. Inside the index.js
file, type in the following
// index.js
alert("hey there")
this will create an alert when the page opens. In order for this to work, we have to attach the JS file to the HTML page. In the <head>
of the index.html
file, add the following: <script src="index.js"></script>
. Now, when you open the index.html
file inside the browser, you should get a popup that saids “hey there”
Congratulations, you have ran your first Javascript code!
Printing to the console
You will find yourself printing to the console many times because it was the first way that most of us where taught to debug code. The idea of printing something to the console is common to most languages, such as C or Java.
To print to the console use
console.log("hey there")
You can also pass in variables:
console.log(myVar1, myVar2)
The semi-colon debate
If you noticed from other programming languages, such as C, each statements are typically ended by a ;
printf("hello there");
However, Javascript does not enforce this practice and you can omit the semi-colon and it makes no difference. console.log("cat")
and console.log("dog");
are both the same in terms of output.
Variables
Variables are how we store data in programming.
Variables in Javascript are stored in a data type called a var
Number
var num = 2
var num2 = num + 1
String
var str = "hi there"
var strCat = str + " hieu"
var singleQuoteStr = "hi there hieu"
Floats
var float = 3.14
var res = float * 2
Boolean
var isTrue = true
var isFale = false
Objects
objects are used when you want to store multiple related data types inside one location.
Object consists of key value pairs.{Key: Value}
var emptyObject = {} // empty object
var dog = {
breed: "golden retriever",
age: 2,
isCute: true,
isDog: true,,
}
//accessing member Variables
console.log("dog breed ", dog.breed)
console.log("dog's age", dog['age'])
if(dog.isDog){
console.log("It is a dog!")
}
you can access a member of an object using the .
operator or the access operator object['NAME_OF_KEY']
Declaring a variable
var declaredVar
Assigning a variable
declaredVar = 2
Comments
// this is a single line comments
/*
this is a
multiline comment
*/
Operators
Operators are how you perform calculations.
Arithmetic operators
var sum = 1 + 2 //3
var difference = 2 - 1 //1
var product = 5 * 100 //500
var quotient = 10 / 2 //5
var remainder = 5 % 4 // 1 because 4 goes into 5 one time with a remainder of 1
var exponent = 5 ** 2 // 25 = 5^2
Incrementing and Decrementing
sometimes you just want to add or subtract by some value.
Incrementing
var value = 10
value = value + 1 // increment by 1 => value = 11
Here we are adding 1 to value
and assigning it back to value
a shortcut for this is:
value++ // this will return the previous value
What is ++
doing?
Here we are saying increase the value by one and return the previous value, which is also called pre-increment
Why?
Sometimes you want to increase a value by one but temporarily reference the previous value
Another way of incrementing is called the post-increment
++value // this will return the value after adding 1
This is similar to pre-increment except that it returns the new value instead of the previous value.
Decrementing
var value = 9
value = value - 1 // decrease the value by 2 and then assign it back to value
shortcut:
value-- // pre-decrement
--value // post-decrement
Assignment Operators
Before we were just incrementing and decrementing by a fixed value of 1. What if we want to multiply or divide? What if we want to do it with some other value besides 1?
That is were assignment operators come in
var value = 100
value *= 2 // multiply value by 2 and assign it back to value
value /= 2 // divide value by 2 and assign it back to value
value -= 10 // subtract 10 from value and assign the result back to value
value += 20 // add 20 to value and assign the result back to value
value %= 3 // take the result of value%3 and assign it back to value
value **= 2 // raise value to the power of 2 and assign the result back to value
String Operator
you can concat or add two strings by using +
var str1 = "hello"
var newStr = str1 + " Devsurvival!"
console.log(newStr) // "hello Devsurvival!"
shortcut:
var str1 = "hello"
str1 += " Devsurvival" // concat "hello" and " Devsurvival" and assign the result to str1
You can also add string and numbers
var donuts = " donuts"
var quantity = 2
console.log(quantity + donuts) // "2 donuts"
Comparison Operators
How to tell if two things are the same or different? We use comparison operators
==
- equal, and doesn’t care if they are not the same type
var sameValue = 2 == "2" // same value but not the same type
// true
===
- equal, and does care if they are the same type
var sameValue = 2 === "2" // same value but not the same type
// false
!=
- not equal to
var notEqual = 3 != "3" // they are the same value
// false
!=
- not equal to and also not the same type
var notEqual = 3 !== "3" // they are the same value, but they are not the same type
// true
>
- greater than
var greater = 1 > 2
// false
<
- less than
var less = 1 < 2
// true
>=
- greater than or equal to
var greaterOrEqual = 2 >= 2 // not greater , but it is equal to 2
// true
<=
- less than or equal to
var lessThanOrEqual = 2 <= 1
//false
Ternary operator
var res = 1 > 2 ? "greater" : "less than"
// res = "less than"
what is going on here?
we are checking if 1 > 2
. If that is true , we return “greater” , else we return “less than”
What does res
contains?
Since 1 is not greater than 2, the condition is false. Since it is false, we return “less than”
Ternary Formula
CONDITION ? if true, return something here : if false, return something here
Logical Operator
Logic operators are how we check more than one conditions at the same time. Let’s say we want to check if the person is over 18 AND owns a car. We can use the &&
operator
var isOver18AndHaveACar = age >= 18 && hasCar
How to check if a person is over 18 OR owns a car
var isOver18OrHaveACar = age >= 18 || hasCar
How to check if a person does not have car?
var doesNotHaveCar = hasCar === false
but there is an easier way
var doesNotHaveCar = !hasCar
the !
operator flips the condition
Array
Array are just a list of items
var strArr = ["one", "two", "three"]
var numArr = [1, 2, 3]
getting an element in array
console.log(arr[0]) // prints the first element in array
getting the length of arrays
console.log(arr.length) // prints the length of the array
Loops
loops are how we iterate over an array
For loop
var i
for (i = 0; i < arr.length; i++) {
console.log(arr[i])
}
- here we are initializing
i
to 0. - We check if
i
is less than the length of the array - If
i
is less than the length of the array, we enter the loop and print the current item at indexi
- We are done with the loop and increment
i
by 1.
Here is the general format of a for loop:
for ( STARTING_VALUE ; CONDITION ; UPDATE THE STARTING CONDITION){
// if CONDITION is true
some code to run here...
// once the code inside the loop is done, we update the starting condition and check the condition again,
// if the condition fails at any point, the loop terminates
}
While Loop
Similar to a for loop, a while loop is used to repeat some code until a certain condition is met
var i = 0
while (i < arr.length) {
console.log(arr[i])
i++
}
In a while loop, we check for some condition. If that condition is true. we enter the loop. We keep repeating until the condition is no longer true and we exit the loop
Do While Loop
A do while loop is similar to a while except, it does executes the code inside the loop at least once regardless of the condition
var i = 0
do {
// do something...
} while (i > 0)
Here you can see that we execute the code inside the do
block and then check the condition. When we check the condition i>0
, we know this is false, and the loop will execute only once.
Condition Statements
Conditional statements are ways we can conditionally perform something.
if (age >= 18) {
// do something that people over 18 can do
}
The above is an if
statement. It checks a condition, and if the condition is true, it executes the code block inside the parenthesis {}
.
Else if and Else
else if
is used following an if
statements to check if it satisfies another condition. You can have multiple else if
, but they all have to follow an if
statement.
an else
statement is used at the very end of the else if
statement when the condition does not satisfies the if
and none of the else if
statements.
if (age >= 18) {
// if they are over 18
} else if (likesDog) {
// if they are not over 18, check if they like dogs
} else if (playsVideoGames) {
// if they are not over 18 and do not like dogs, check if they play video games
} else {
// if they are not over 18, do not like dogs, and do not play video games
}
Switch
switch
are often used when you have many conditions to check for.
For instance
switch (favoriteFood) {
case "pizza":
console.log("you liked pizza!")
break
case "donuts":
console.log("you like donuts!")
break
case "steak":
console.log("you like steak!")
break
default:
console.log("you like", favoriteFood)
}
Here you are testing the variable favoriteFood
and you have a set of cases that you are testing for pizza, donuts, and steak
. If the case matches, you enter the statement, execute the code, and then break
which exits from the switch. Make sure you have a break at the end of each case statement.
You can also provide a default case which will be executed if none of the cases matches the test value.
Functions
Functions are reusable blocks of code that we can pass different parameters into and get a different output.
Let’s see how we can create a function
function bark() {
console.log("woof!")
}
Here we have a function called bark
.
How do we use it? simple.
bark() // invoking or calling the function bark();
Passing parameters
you can make a function for dynamic by passing parameters
function bark(nameOfDog) {
console.log(nameOfDog + " barked!")
}
here we are passing in the nameOfDog
and console.log(nameOfDog + " barked!")
Invoked the function:
barked("Charlie") // "Charlie barked!"
Returning a value
It is great that a function can perform things, but what about getting some return value from it? Javascript functions can also return a value after performing some kind of calculations
function double(num) {
return num * 2
}
var doubledValue = double(3) // doubledValue = 6
This function accepts a num
and returns the number after it has been doubled.
Anonymous Functions
Anonymous functions are functions without a name
// normal functions
function fnNAme(){
}
//anonymous functions
function(){
}
When To Use Anonymous Function?
When you need to pass a function definition into a another function without declaring the function explicitly. Let’s learn with an example
// traditional way of passing a function to another function
function fn1() {
console.log("this is function 1")
}
function run(fn) {
fn() // invoked the function that was passed in
}
// passing fn1 to run()
run(fn1)
// The code above can be simplified using anonymous function
function run(fn) {
// same as before
fn()
}
// passing in the anonymous function
run(function() {
console.log("this is function 1")
})
This is useful when you want to pass in a function that will not be referenced anywhere else and will only be used temporarily.
What’s Next?
Learn some advanced Javascript using ES5 and ES6 in part 2 of learning Javascript