Console.log(
Variables in JavaScript, which I will be referring to as JS from now on, is relatively similar to python.
First, we have the ‘let’ variable type. ‘let’ is a variable type put before the variable, but functions just like a normal python variable. you can reference it, you can change it, all that good stuff.
Writing a ‘let’ variable would look like this:
let test = 'test';
As you can tell, it is very much like a normal python variable, except with ‘let’ in the beginning.
Now, you may be wondering, why would we need that extra step? Well, to differentiate from our next variable type, called ‘const’, short for ‘constant’ such as the ones we use in Python. While in python, they are variables that SHOULDN’T be changed, normally in all caps, ‘const’ are variables that CANNOT be reassigned.
For example, if you were to write
const test = 'test';
test = 'testing';
You would get an error. This is because as a ‘const’ variable type, it cannot let you reassign it, as that is its job. To stay the same. This likely helps prevent accidental alteration of a variable you don’t want to change.
However, they are not completely immune to change. Consider you have a list, which would be written like
const nums = [1,2,3];
While we cannot reassign it, we can still alter it.
const nums = [1,2,3];
nums.push(5);
Push puts the number onto the end of the list, but that is not what this is about. If you were to print this, it would give you [1,2,3,5] as it is now altered. It has not been directly reassigned, so it does not give you an error.
Lists, you say? What about dictionaries? Of course, they exist here too. Writing a dictionary in JS would look something like
const cats = {
cat1:"Calico"
cat2:"Silver Tabby"
};
Despite being a constant, this can also be altered through non-direct reassignment, like the lists can.
You can directly address a certain dictionary like so
console.log(cats.cat1);
Which will give you “Calico” in your terminal.
Finally, there is the functions. Very important, of course. To write a function in JS would look something like this
function sayMeow() {
console.log("Meow")
};
Of course, functions in JS work just like python functions. They run the code inside them when called upon.
This covers most of the basic variable types you will find in JS as of being a starter. I’m certain more complicated things are to come, but it doesn’t hurt to go over the basics!
Leave a Reply