{ "cells": [ { "cell_type": "raw", "id": "7686b654", "metadata": { "vscode": { "languageId": "raw" } }, "source": [ "---\n", "layout: post\n", "toc: True\n", "breadcrumb: True\n", "title: JS Variables Lesson\n", "description: This lesson explains how to use JavaScript variables.\n", "permalink: /csse/javascript/fundamentals/variables-lesson\n", "author: Samarth H, Anish G, Krish K, Pranay K\n", "---\n" ] }, { "cell_type": "markdown", "id": "7dc36bf3", "metadata": {}, "source": [ "\n", "\n", "Presented by the\n", "

TINKERERS

\n", "\n", "
\n", "\n", "## Variables Lesson Intro\n", "\n", "In this lesson, you will be learn the basics of variables. This includes what they are, how to use them in Javascript, and where they can be applied. Let's dive in!\n", "\n", "## What a Variable Even Is\n", "\n", "- A variable is a container that can store information\n", "- Analogy: Cardboard box where you can put notes or whatever you want in" ] }, { "cell_type": "code", "execution_count": 8, "id": "d4a51138", "metadata": { "vscode": { "languageId": "html" } }, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "

JavaScript Variable Demo!!

\n", "

Click the buttons to see how a variable changes.

\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Variable not declared yet.
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%html\n", "\n", "\n", "\n", "\n", "\n", "

JavaScript Variable Demo!!

\n", "

Click the buttons to see how a variable changes.

\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Variable not declared yet.
\n", "\n", "" ] }, { "cell_type": "markdown", "id": "3a92df88", "metadata": {}, "source": [ "## How we used variables\n", "\n", "In our wordgame from last sprint, we used variables to:\n", "- Store strings that would be typed by a user\n", "- Store the time the user started\n", "- Store the accuracy once it's calculated\n", "- etc.\n", "\n", "## Examples of Variables in our Wordgame\n", "\n", "Look below for an example of a variable in our wordgame!\n", "\n", "```js\n", "const short_strings = [\"The quick brown fox jumps over the lazy dog\", \"Pack my box with five dozen liquor jugs\", \"How quickly daft jumping zebras vex\", \"Jinxed wizards pluck ivy from the quilt\", \"Bright vixens jump dozy fowl quack\", \"Sphinx of black quartz judge my vow\", \"Two driven jocks help fax my big quiz\", \"Five quacking zephyrs jolt my wax bed\", \"The five boxing wizards jump quickly\", \"Jackdaws love my big sphinx of quartz\", \"Quick zephyrs blow vexing daft Jim\", \"Zany gnomes fix blighted quartz vases\", \"Bold foxes jump quickly past the lazy hound\", \"Mix two dozen plums with five ripe figs\", \"Anish is the GOAT\"];\n", "```\n", "\n", "Here's another example of variables being used at the beginning of Word Game.\n", "\n", "```js\n", "const wordCanvas = document.getElementById('wordCanvas');\n", "const wordCtx = wordCanvas.getContext('2d');\n", "const optionsButton = document.getElementById('options');\n", "const progressFill = document.querySelector('.progress-fill');\n", "const progressText = document.querySelector('.progress-text');\n", "\n", "const wpmEl = document.querySelector('.wpm');\n", "const accEl = document.querySelector('.accuracy');\n", "if (wpmEl) { wpmEl.style.visibility = 'hidden'; wpmEl.textContent = ''; }\n", "if (accEl) { accEl.style.visibility = 'hidden'; accEl.textContent = ''; }\n", "\n", "let currentString = \"\";\n", "let userInput = \"\";\n", "let startTime = null;\n", "let finished = false;\n", "let mistakes = 0;\n", "let currentPrompt = \"\";\n", "let caretInterval = null;\n", "```" ] }, { "cell_type": "markdown", "id": "c5ded79c", "metadata": {}, "source": [ "\n", "## General Examples of Variables\n", "\n", "Here are some examples of variables:" ] }, { "cell_type": "code", "execution_count": null, "id": "09f27dd6", "metadata": { "vscode": { "languageId": "javascript" } }, "outputs": [], "source": [ "var hello = \"Hello, I am a string.\";\n", "let hi = 0;\n", "const hey = 3.4;" ] }, { "cell_type": "markdown", "id": "af3e5d27", "metadata": {}, "source": [ "Now let's answer the following questions:\n", "\n", "+ What do the keywords `var`, `let`, and `const` do?\n", " + How are they different?\n", "+ What are `hi`, `hello`, and `hey`?\n", "+ What does the `=` symbol do?\n", "+ What are the values after the `=`?\n" ] }, { "cell_type": "markdown", "id": "83ed5faa", "metadata": {}, "source": [ "# Lesson Cont...\n", "\n", "Now since we have an initial feel for variables, let's continue our investigation into the subject.\n", "\n", "Variables can be declared by `var`, `const`, and `let`. \n", "**IMPORTANT**: `var` is now deprecated, so it is best practice to not use it. It's the old way of defining variables, so avoid using this one.\n", "\n", "`const` REQUIRES a var to never change later. We use `let` if we want to change the var later.\n", "\n", "\n", "## Defining variables\n", "To define variables, use `var`, `const`, or `let` as your keyword, followed by the name of your variable, an equal sign, the value assigned to the variable (optional), and a semicolon. You should try to make your variables descriptive but not too long.\n", "\n", "Here is a common naming convention for JavaScript variables:\n", "\n", "- All lowercase if variable is just one word\n", "- camelCase is variable is 2+ words\n", "\n", "Examples\n", "```js\n", "\n", "// Defines a variable named score with value 20.\n", "let score = 20; \n", "\n", "// Here, a variable has been defined but its value is undefined.\n", "let age; \n", "\n", "/*\n", "When we change the value of a variable after defining it with let/const/var,\n", "you DON'T need to redefine it again - i.e. you don't need to use let, const\n", "or var again.\n", "*/\n", "age = 67;\n", "\n", "// What does myvar refer to? What does it represent?\n", "// You should avoid vague names like below.\n", "// Variables should be concise and descriptive.\n", "const myvar = 3;\n", "\n", "// This will raise an error, as constants are... well... constant\n", "// myvar = 20;\n", "\n", "// You should also avoid variable names that are ridiculously long.\n", "// (this is exaggerated but please don't do this lol)\n", "let accumulatedScorePointsVariableUsedForDeterminingFinalOutcome = 20;\n", "```\n", "\n", "## In Our Wordgame...\n", "\n", "In our wordgame, we used `const` to define the lists of possible strings since we aren't going to change the list of strings that the user might have to type. We also properly named our variable, and used an equal sign to declare the var to it's specified value.\n", "\n", "## Equal Sign\n", "\n", "> Did you try removing the equal sign?\n", "\n", "Removal of the equal sign would have caused an error. the `=` symbol is what TELLS javascript that a variable is being declared and initialized. The `let` and `const` keywords are there to say what *type* of variable we are using.\n", "\n", "# Popcorn Hack 2\n", "\n", "It's time for a 2nd poporn hack!" ] }, { "cell_type": "markdown", "id": "8021f6fe", "metadata": {}, "source": [ "# A brief note on Data Types\n", "\n", "As you may have noticesd, there are a lot of different kinds of values we can store. These are called **data types**.\n", "\n", "Going very in-detail on data types is outside the scope of this lesson, but here's a brief overview with examples from Word Game.\n", "\n", "- Number\n", " - Some other programming languages have integers and floats.\n", " - JavaScript has just one data type called `Number`.\n", " - In word game, the variable `mistakes` contained a number.\n", "\n", "- String\n", " - A \"string\" of text surrounded by quotes.\n", " - In word game, this code `let currentString = \"\";` gives currentString the value of an empty string.\n", " - Warning: \"16\" and 16 are DIFFERENT because one is a Number and one is a String.\n", "\n", "- Booleans\n", " - True/False values\n", " - In the `finishGame()` function in Word Game: `finished = true;`\n", " - Note that we didn't need to use `let`, as we had already done that\n", "\n", "- Null\n", " - To represent an intentionally empty value.\n", " - Word Game example: `startTime = null;` just tells the computer that startTime has a empty value.\n", " - This is different from `undefined`, which is set by JavaScript\n", " - For example, when you define a variable like `let x;`, x will be undefined until given a value\n", "\n", "- And others! (Object, BigInt, Symbol, Date, etc.)\n", "\n", "\n", "# Ending notes\n", "\n", "Nice! You've learned about variables and used higher-level thinking skills! For our lesson's end, we will give you this cheat sheet:\n", "\n", "In a JS declaration such as this:" ] }, { "cell_type": "code", "execution_count": null, "id": "379ec2eb", "metadata": { "vscode": { "languageId": "javascript" } }, "outputs": [], "source": [ "let var_name = \"Value\";" ] }, { "cell_type": "markdown", "id": "e6694ac1", "metadata": {}, "source": [ "- `let` can be replaced with `const` if you aren't changing the var name later.\n", "- `var_name` can be replaced with any valid variable name (any alphanumeric charecter or the `_`, cannot start with a number)\n", "- `=` is necessary for proper declaration\n", "- `\"Value\"` can be changed to any value that you want to store, whether a string or a number\n", "\n", "# Ending\n", "\n", "That's it for the lesson! Remember to try the homework as well! It should take ~30min!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.6" } }, "nbformat": 4, "nbformat_minor": 5 }