Variables are “containers” that store values
Variables can have different values: numbers, texts, booleans (true, false), HTML elements
Constants vs Variables
Constant: variables that do not change
Variables: variables that do change
3. Different Types of Variables
JS Types are Dynamic: you can change the type of the variable to whatever you want, even if it’s different from your initial assignment
With decimals: 24.05
Without decimals: 23, 24
Do typeof to check the type of a variable.
You declare variable in JS by using var keyword.
var x = 30; //You declared a variable called x with value of 30. var text = 'hi'; //You declared a variable called text with value 'hi'. typeof text; //this will return 'text'
4. Math Operators
Codepen does not print out the results directly on to your HTML result screen, because you are not giving any commands to print the results of your math equation onto your HTML webpage. Instead, you can use 'inspect' panel of Chrome.
1) Right click anywhere on your google Chrome page
2) Select Inspect
3) Select Console panel from the top
4) Type in your JS code!
5) Try using math operators! (Hit enter when you are done with writing your JS code!)
Sometimes you need to add 1 to a variable repeatedly (in a loop).
You can do so by:
x = x + 1;
Similarly, when you need to subtract 1 from a variable,
You can do:
x = x - 1;
6. Math operator part 2:
There are two ways to do this:
You should get:
Try this link:
Using document.write(), we can directly interact with HTML.
document.write() is used to add new text to your HTML.
Your new text added to HTML will not be encapsulated in a HTML tag.
And the new text will be added at the end of all elements you have.
This will print 9 on your webpage.
Here, I defined two HTML elements: h1 element with class title and p element with id paragraph.
In JS, if you want to fetch an element with certain name/class/id, you do:
Similar to CSS, you use period (.) when you want to tell JS that you are looking for a class with the following name. e.g.
For id, you use hashtag (#):
If you want to get element with certain tag, you do:
You can set a variable to have HTML element as its value.
var title = document.querySelector('.title');
You can modify content within HTML tags of your selected element using innerHTML.
document.querySelector('.title').innerHTML = 'Hey!';
Since you have assigned the above element to a variable, you can also change the content by calling innerHTML method on the variable:
title.innerHTML = 'Hey!';
Experiment with this here: