JS Introduction and Variables
#
Brief Introduction to JavaScriptJavaScript is a programming language used primarily by Web browsers to create a dynamic and interactive experience for the user. Most of the functions and applications that make the Internet indispensable to modern life are coded in some form of JavaScript. In the past, Web pages were static, offering little user interaction beyond clicking links and loading new pages. For the first time, JavaScript enabled animation, adaptive content and form validation on the page. Now, most modern browsers support the latest JavaScript updates.
Some of the dynamic website enhancements performed by JavaScript are:
- Autocompletion
- Loading new content or data onto the page without reloading the page
- Rollover effects and dropdown menus
- Animating page elements such as fading, resizing or relocating
- Playing audio and video
- Validating input from Webforms
- Repairing browser compatibility issues
#
WhyWe use variables to provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.
#
What#
VariablesVariables are used to store information to be referenced and manipulated in a computer program. A variable is essentially a memory location where a value is stored. A variable is referred to by an identifier, or name, and can hold a JavaScript value of any type.
We can create and give a variable a value like so:
In the example, we create, or declare, a variable named count
, and give, or assign, it a number value with = 10
.
We gave the variable the name count
, which is all-lowercase letters. We actually can use uppercase letters and even a few symbols in our variable names.
Programming languages require certain naming conventions for variable identifiers. JavaScript requires the following rules:
- A JavaScript identifier must start with a letter, underscore (
_
), or dollar sign ($
). Subsequent characters can also be digits (0–9
) - Because JavaScript is case sensitive,
apple
,Apple
, andAPPLE
are all different names - Multi-word identifiers should be camel cased, where each new word is capitalized
- Ex:
thisIsCamelCased
- Ex:
- Some examples of valid names are:
Number_hits
,temp99
,$credit
,_name
, andtopScore
Although camel casing is popular in JavaScript, it is not required. Alternatives to camel casing are Pascal Casing (ex:
ThisIsPascalCasing
) or underscores (ex:this_uses_underscores_for_each_space
)
Naming variables can be one of the most difficult tasks in computer programming. When you are naming variables, think hard about the names. Try your best to make sure that the name you assign your variable is accurately descriptive and understandable to another reader. A reader should be able to read a variable name and understand its use in your program without supplemental documentation. This is one way to make your code self documenting.
Like above, you assign a value to a variable by using the =
assignment operator.
The name of the variable goes on the left-hand side and the value you want to store in the variable goes on the right-hand side of the assignment operator.
#
How#
Declaring and Assigning VariablesYou can declare a variable with one of three declaration keywords:
var
- creates a function-scoped variable whose value can be reassignedlet
- creates a block-scoped variable whose value can be reassignedconst
- creates a block-scoped variable whose value cannot be reassigned
Examples:
undefined
values are automatically assigned to variables that have just been declared (but not assigned an initial value), or to formal arguments (parameters) for which there are no actual arguments.
#
JavaScript Data TypesNow that we know we can create variables to store data in our programs, we'll introduce the different types of data we can use in our programs.
#
Primitive Data Types- Used as a value that doesn't exist, or no longer exists
- Ex:
let petName = undefined;
- Used as a value that is empty, or is an invalid value
- Ex:
let petName = null;
- Used for logical values, true or false; yes or no; on or off
- Ex:
let isOnline = true;
- Used for any number value; integer, floating point, decimal, etc
- Ex:
- Used for text values
- Single or double quotes surround the text values
- Backticks can be used. Using backticks is referred to as a template literal string
- Ex:
- Used for very large numbers with arbitrary-precision format
- Ex:
- Used as unique keys as property names on objects
- Ex:
NOTE: Primitives cannot be altered. Remember that a primitive itself is different from the variable assigned a primitive value.
Variables may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.
NOTE: A primitive can be replaced, but it can't be directly altered.
#
Structural (Non-primitive) Data Types- Used to store complex, related values represented as key/value pairs
- *Will be discussed in a later lesson
- Used to created callable code blocks
- *Will be discussed in a later lesson
- Ex:
#
Data Type ConversionJavaScript is a dynamically typed language. This means you don't have to specify the data type of a variable when you declare it. It also means that data types are automatically converted as-needed during script execution.
So, for example, you could define a variable as follows:
And later, you could re-assign the same variable a string value, for example:
Because JavaScript is dynamically typed, this assignment does not cause an error message.
If you re-declare a JavaScript variable, it will not lose its value. The variable carName will still have the value "Volvo" after the execution of these statements:
NOTE: The above example only works if you declare a variable using the keyword
var
. As of ES2015, usinglet
orconst
will disable your ability to redeclare variables.
#
Duck TypingJavascript is an interpreted language, meaning the interpreter assigns variables a type based on the variable’s value at run-time.
Moreover, interpreted languages are languages that are not compiled but are parsed upon execution. Javascript and other languages fall into this category, as you don’t have a compile step prior to running. Simply save the script and refresh.
When referring to Duck Typing, many use the saying, "If it quacks like a duck, walks like a duck...it’s a duck."
Duck Typing refers to a duck test program. You will test something, if it quacks like a duck, and walks like a duck, it is a duck. If a method responds to any given object call, it passes the "Duck Test".
Duck Typing is a feature in JavaScript where the variable attempts to behave in the manner it is used. So if it’s used as a string, it’s a string, etc.
In C# or other statically typed languages, passing methods into objects is deemed suitable based on its type. With duck typing, however, objects are determined whether or not suitable based on what it does, not what it is. It doesn’t matter the type if both objects do the same thing or better yet, have the same capabilities. If the method responds to the object call, basically as long as the object responds type doesn't matter.
Duck Typing is polymorphism without hierarchy, dynamic dispatch without inheritance hierarchy, and no explicit interfaces. Essentially checking for capability, not compatibility.
Duck Typing is used in many programming languages, Ruby and Python for example, and it is really useful. However, sometimes it creates unwanted results in an application because the rules of Duck Typing are too simple and can result in wrong conclusions. You can understand this warning more in examples below.
#
Type CoercionA central pillar of JavaScript involves the core concept called Type Coercion. Type Coercion is the interpreted nature of JavaScript to morph a data type from one to another based on the attempt to complete an action. For example, if you try to perform an arithmetic operation between a number and a string, JavaScript will change one of the two values to match the other.
For the most part, it makes sense. You can't perform addition when one of the two values isn't even a number. JavaScript recognizes that and will try to interpret your intention to give a result. Let's take a look:
Type Coercion is central to how JavaScript will interpret and execute your program. We will cover more examples in a future lesson with JavaScript Operators.
#
Seeing Your WorkAs we begin to learn more about the JavaScript language, it's helpful to see print outs of what we are doing. You can print values to the browser console with console.log("value")
.
To view the browser console, you can right-click the page and select "Inspect...", or press fn + F12 to open up your browser's developer tools. Once you open the developer tools, toggle the tab labeled "Console". There you will see any value passed inbetween parentheses to console.log("Will be logged to the browser console.")
.
#
Takeaways- JavaScript is a dynamically typed, interpreted scripting language used to create rich and dynamic user interfaces and experiences on webpages
- Variabes are containers for values that you can use to pass and reference elsewhere in your program
- Type Coercion is a feature of JavaScript where values are converted, or coerced, to another data type depending on the operations being attempted