In this module, you are introduced to JavaScript. You’ll learn why JavaScript is so integral to software development. And you’ll get an overview of how to write JavaScript code inside the browser. Furthermore, you will learn about the most common operators as well as conditional statements and loops. After completing this module, you will have completed the following learning objectives:
Learning Objectives
- Explain the importance of JavaScript in software development
- Demonstrate how to write JavaScript code inside the browser
- Demonstrate how to write basic JavaScript code: List common operators, conditional statements and loops
- Demonstrate how to use variables and output their values in the console
- Setting up
- Welcome to Programming
- Video: Introduction to programming
- Video: Why JavaScript?
- Video: Programming in JavaScript
- Reading: Writing your first Javascript code
- Video: Variables
- Reading: Exercise: Declaring variables
- Reading: Declaring variables (solutions)
- Video: Data types
- Video: Operators
- Video: Numbers
- Video: Strings
- Video: Booleans
- Reading: Operators in depth
- Reading: Exercise: Advanced use of operators
- Reading: Advanced use of operators (solutions)
- Practice Quiz: Knowledge check: Welcome to Programming
- Reading: JavaScript improvements
- Reading: Additional resources
- Conditionals and Loops
- Video: Writing statements
- Video: Working with conditional statements
- Reading: Conditional examples
- Reading: Exercise: Practice conditional statements
- Reading: Solutions: Practice conditional statements
- Video: Looping constructs
- Video: For loop
- Video: While loop
- Reading: Exercise: Repetitive tasks with loops
- Reading: Repetitive tasks with loops (solutions)
- Video: Nested loops
- Reading: Loops and nested loops
- Reading: Uses of loops
- Reading: Exercise: Working with conditionals and loops
- Reading: Solution: Working with conditionals and loops
- Practice Quiz: Knowledge check – Conditionals and loops
- Video: Module summary: Introduction to JavaScript
- Quiz: Module quiz: Introduction to JavaScript
- Reading: Additional resources for Conditionals and Loops
Setting up
Video: Introduction to Programming with JavaScript
This course provides a comprehensive introduction to JavaScript, equipping you with the skills to become a software developer:
Key takeaways:
- JavaScript powers web interactivity: From search engines to social media, JavaScript makes your online experience dynamic.
- Beyond front-end: JavaScript now tackles back-end development and mobile app creation with frameworks like React.
- Module breakdown:
- Module 1: Introduction – Setting up your environment, exploring variables, data types, operators, and basic control flow.
- Module 2: Building blocks – Arrays, objects, functions, and debugging basics.
- Module 3: Paradigms and features – Functional programming, object-oriented programming, destructuring, template literals, data structures, and browser interaction.
- Module 4: Testing and compatibility – Unit testing with Jest, test-driven development, JavaScript challenges, and other environments like Node and NPM.
- Module 5: Project – Applying your skills to build a “little lemon receipt maker” application.
Bonus:
- Don’t worry if you encounter unfamiliar terms – everything will be clarified as the course progresses.
Remember: This course is your stepping stone towards a rewarding career in software development!
Overall:
This summary provides a concise overview of the course’s content and target audience. It highlights the key takeaways and the learning journey, making it easier for potential students to understand the value proposition.
Welcome to the exciting world of JavaScript! This tutorial will guide you through the fundamentals of this versatile language, empowering you to build interactive web experiences and unlock your coding potential.
1. Setting Up Your Playground:
- Choose your editor: Download a user-friendly editor like Visual Studio Code or Sublime Text.
- Install a browser extension: Chrome DevTools or Firefox Developer Tools provide invaluable debugging and inspection capabilities.
- Get comfortable with the console: Learn to print messages and experiment with code in your browser’s console.
2. Hello, World! Your First Steps:
- Variables: Store information like text or numbers and use them later in your code.
- Data types: Understand different types like strings, numbers, booleans, and arrays to handle data accurately.
- Basic operators: Master arithmetic (+, -, *, /) and comparison (==, !=, >, <) operators to perform calculations and make decisions.
3. Building Blocks of Logic:
- Control flow: Learn to control the execution of your code using conditionals (if/else) and loops (for/while/do-while) based on specific conditions.
- Functions: Create reusable blocks of code that perform specific tasks, making your code cleaner and more efficient.
4. Interactive Elements:
- DOM manipulation: Learn to access and modify HTML elements directly in your web page using JavaScript, creating dynamic experiences.
- Events: React to user interactions like clicks, scrolls, and key presses to build responsive and engaging web applications.
5. Beyond the Basics:
- Objects: Organize data and functionality into structured units, allowing for complex data manipulation and logic.
- Modern JavaScript features: Explore features like arrow functions, classes, and modules to write concise and maintainable code.
- Testing your code: Ensure your code works as expected by writing unit tests using frameworks like Jest.
6. Practice Makes Perfect:
- Start small: Begin with simple exercises and gradually build your skills by tackling more complex projects.
- Seek resources: Utilize online tutorials, documentation, and communities to overcome challenges and accelerate your learning.
- Build something real: Apply your knowledge to create interactive prototypes, web games, or single-page applications to showcase your skills.
Remember: Programming is a journey, not a destination. Embrace the challenges, celebrate your progress, and keep learning. With dedication and passion, JavaScript can be your key to unlocking endless possibilities in the world of web development!
Bonus Resources:
- Interactive tutorials: Codecademy, FreeCodeCamp
- Documentation: Mozilla Developer Network
- Communities: Stack Overflow, Reddit
- Online courses: Coursera, edX
Start your JavaScript adventure today and build the web of tomorrow!
So much of what you take for granted in your
everyday online life, like using a search
engine, shopping, and using social media, is made possible by JavaScript. Nearly all of the interactivity
you experience online, like drop-down menus or
the autocomplete function, is facilitated by JavaScript. JavaScript is most
well-known for being the programming
language of the web. But it has become so much more. Now, it is used not only for
the front-end development, but also for back-end
development, and you can even create mobile apps using
JavaScript and React. Without JavaScript, the modern software
development landscape would look a lot different. Because it is such
a powerful tool and so integral to
software development, it is important for you, as a new developer, to know how it works
and how to use it. In this course,
starting with Module 1, you will cover an
introduction to JavaScript, that will help you
understand how it is used in the real-world. You’ll learn how to set up Visual Studio Code and install the code
runner extinction. This module also introduces you to programming
in JavaScript, which includes learning
about variables, datatypes, operators, strings,
booleans, and numbers. After this, you’ll
progress to learning about conditional
statements and loops. In Module 2, you will build on what you’ve learned in the first module, by learning about arrays,
objects, and functions. You will also learn
about bugs and errors. In Module 3, you will learn about the
functional programming and object-oriented
programming paradigm, which includes function
calling, recursion, and scope. With scoping, you
will learn how to use var, let, and const. Furthermore, you will learn about object-oriented
programming, and you will design and build
an object-oriented program. You will also learn about
advanced JavaScript features, like destructuring
arrays and objects using four of loops
and template literals. Additionally, you
will learn about data structures and the
spread and rest operators. You will also learn how JavaScript is used
in the browser. In this module, you will
have an opportunity to practice updating the
contents of a webpage. Module 4 is all about
testing and compatibility. Therefore, you will
learn about types of testing and you’ll
write a unit test. You will also be
introduced to Jest and learn how to write tests
with Jest in an exercise. You will learn about
test-driven development and get to practice
applying it too. You will also learn about
JavaScript testing challenges, which include learning
about webpack, transpiling, and working with
arrow functions in React. As part of this module, you will also learn about
other JavaScript environments, like Node and NPM. In Module 5, you will have an opportunity
to put your new skills into practice by creating the
little lemon receipt maker. In summary, this course provides you with an introduction
to JavaScript. It is part of a program
of courses that leads you towards a career
in software development. You have probably encountered many new technical words and
terminology in this video. Don’t worry if you don’t fully understand all these
terms right now, everything will
become clear soon. After all, this is part of the reason why you were
taking this course.
Video: How is JavaScript used in the real world?
JavaScript: The Ubiquitous Language of the Web and Beyond
- Murtadha, a seasoned JavaScript engineer at Meta, introduces the importance and ubiquity of JavaScript.
- JavaScript is everywhere: From websites and coffee makers to cars, it’s the dominant language of the internet and modern devices.
- Web development’s sole language: Unlike other applications with various options, web development relies solely on JavaScript.
- Front-end and back-end: JavaScript’s unique ability to handle both front-end and back-end development simplifies application design and maintenance.
- Challenges and quirks: While sharing similarities with other languages, JavaScript has its own unique nuances and inconsistencies.
- Learning curve: Despite challenges, Murtadha finds JavaScript easier to learn than its counterparts.
- Perseverance and reward: Embrace the challenges and enjoy the journey of learning and loving this powerful language.
- Essential skill for developers: Mastering JavaScript opens doors to numerous career opportunities in the tech landscape.
- Give it a try: Don’t let initial frustration deter you. Persevere and unlock the potential of this ubiquitous language.
Key Takeaways:
- JavaScript’s dominance in web development and its versatility make it an essential skill for modern developers.
- Learning JavaScript can open doors to exciting career opportunities in various tech fields.
- Embrace the challenges and enjoy the journey of mastering this powerful and ubiquitous language.
JavaScript, once confined to simple website animations, has evolved into a powerhouse language powering the interactive elements we encounter daily. From dynamic web pages to mobile apps and beyond, JavaScript’s reach is vast and ever-expanding. Let’s dive into some real-world examples of how JavaScript is used:
1. Web Development:
- Interactive Web Pages: JavaScript breathes life into websites, enabling features like drop-down menus, image sliders, and dynamic content updates. Imagine a shopping website where you filter products based on price or color – that’s JavaScript at work!
- Single-Page Applications (SPAs): These modern web applications load a single page initially and then dynamically update content without refreshing the entire page. Think Gmail or Facebook – their seamless interaction is powered by JavaScript.
2. Mobile Apps:
- Native Mobile Apps: Frameworks like React Native and Ionic allow developers to build native mobile apps for iOS and Android using JavaScript. This saves time and resources, as developers don’t need to learn separate languages for each platform.
- Progressive Web Apps (PWAs): These web apps offer app-like experiences on mobile devices, leveraging features like push notifications and offline functionality. PWAs are built with JavaScript and can be accessed through any web browser.
3. Game Development:
- Browser Games: From casual puzzle games to complex strategy simulations, many popular browser games are built using JavaScript frameworks like Phaser and PixiJS. These frameworks provide tools for animation, physics simulation, and sound effects.
- Mobile Games: JavaScript frameworks like Unity and Babylon.js are increasingly used to develop 2D and 3D mobile games. These frameworks offer powerful graphics engines and cross-platform capabilities.
4. Beyond the Web:
- Internet of Things (IoT): JavaScript is finding its way into smart devices like thermostats, wearables, and home automation systems. These devices use JavaScript to communicate with each other and the internet.
- Server-Side Development: Node.js, a JavaScript runtime environment, allows developers to build server-side applications. This means JavaScript can now handle both the front-end and back-end of web applications.
5. The Future of JavaScript:
- Emerging Technologies: JavaScript continues to evolve with new frameworks and libraries emerging for areas like artificial intelligence, machine learning, and virtual reality. The future holds exciting possibilities for JavaScript’s applications in these cutting-edge fields.
Learning JavaScript:
If you’re curious about exploring the world of JavaScript, numerous resources are available to help you get started. Online tutorials, interactive coding platforms, and bootcamps can equip you with the skills to build your own interactive web experiences and mobile apps.
Remember, JavaScript is a versatile and powerful language with endless possibilities. So, dive in, explore, and unlock the potential to create something amazing!
Additional Resources:
- FreeCodeCamp: https://www.freecodecamp.org/
- Codecademy: https://www.codecademy.com/
- Khan Academy: https://www.khanacademy.org/computing/computer-programming
- Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/JavaScript
Anytime you’re using a browser, anytime you’re
browsing the Internet, you are using JavaScript. It’s the language
of the Internet. My name is Murtadha.
I’m a software engineer at Meta based in
the Seattle office. I’ve been coding in
JavaScript since 2012, so JavaScript is actually something that as you’re watching me now
through this video, it’s something that you’re using probably as you made your
coffee this morning, maybe your coffee maker
had some JavaScript, your car might have JavaScript. Nowadays, we are in a
world where JavaScript is so common and so used across a lot of technologies and a lot of devices that it’s become a language that
cannot be replaced. The first time I
use JavaScript was, I was an intern at the
time Facebook and then the time JavaScript had not been as popular and as common. I hadn’t actually learned it in university
or in my courses. The other more attractive or interesting
languages at the time were people writing in
Java or C plus, plus. People used to
sometimes not take JavaScript very
seriously and think like it’s a language that’s not used by real and
serious developers. But now we see the world
runs using JavaScript and just about every application
we interact with today probably has
some JavaScript in it, one way or another. What are the things that
makes JavaScript so popular and important
is that it’s the only language that is
used in web development. In game development or other
types of applications. There are choices to use
other languages like you could use C plus plus
or you could use Java, or you could use other things. But when it comes
to web development, the only available
language is JavaScript, and that’s what makes it
so popular and common and important to learn when you’re developing
web applications. At Metta, we use JavaScript
in our entire web stack, but we also use JavaScript
in other places too. One of the unique
things about JavaScript that no other language has is that it’s a language
that can be used for writing the front-end
and the back-end, so a lot of applications,
they have a back-end, maybe in Python or PHP or
Java or something else. But they’re required to have a JavaScript front-end
because that’s the only language
of the front end. But because JavaScript can also be used on the backend if you design your application
and if you choose to make it consistently JavaScript
across the entire stack, sometimes that may simplify the application and then
you don’t have to learn multiple languages or maintain code bases that are written
in different languages. Some of the challenges that I faced when switching
between other languages, like I had been used to Java and came to the
world of JavaScript. Even though they seem
like they might be very similar they’re like half
of the name is the same. But actually it
turns out there are some things in
JavaScript that are specific and they are very
unique to its language. There are certain things about JavaScript that are a
little inconsistent when compared to other
programming languages like you have your C plus plus and Java and
some other languages that follow certain behaviors, and then JavaScript is sometimes in its own
corner doing weird things. But I actually find
that a lot of times JavaScript is easier to learn than some of
these other languages, so even in its weirdness and in its quirks and some of the things that are
confusing about it, overall, I find it
an easier language to learn and use than
these other ones. As you’re learning JavaScript, you’ll stumble upon
challenges and you might find that things
are not making sense. I encourage you to
power through them, and you will find
that with time, you will likely come to enjoy
and love this language. At this point, we live in
a world where JavaScript is so commonly used across
devices and technologies. I can’t comprehend or think of all the different
applications or places that are running
JavaScript in them. As you as developer
who’s learning coding, it’s an important skill to have and you’ll find that
many employers will be interested in hiring you if you can code in JavaScript. Give it a shot and
be patient with it. If it confuses you
or frustrates you, don’t let that stop you
from going through. Do the thing at the end too.
Video: Setting up VS code
1. Installing VS Code:
- Download VS Code from the official website.
- Select the Download for Windows button.
- Accept the license agreement and choose the installation options.
- Click Install and Finish.
2. Installing Code Runner extension:
- Open the Extensions panel in VS Code.
- Search for and install the Code Runner extension.
3. Installing Node.js:
- Download the Windows version from Node.js.org.
- Run the setup wizard, accept the license, and click Install.
- Click Finish to close the wizard.
4. Setting up VS Code for JavaScript:
- Open a new file and select JavaScript as the language.
- Close the Code Runner tab and toggle off the extension sidebar.
- Open and dock the Terminal window on the right side.
- Clear the Terminal and adjust the output width if needed.
5. Running your first JavaScript code:
- Type
console.log("Hello World")
in the code editor. - Run the code using the Play icon or the Control + Alt + N shortcut.
- Verify that “Hello World” is printed in the output.
Congratulations! You are now ready to start writing and running JavaScript code in VS Code on Windows.
Bonus:
- The video also explains the purpose of
console.log
in JavaScript, which is to print messages to the console.
Ready to embark on your coding journey with JavaScript? VS Code, a powerful and user-friendly code editor, is your ideal companion. This tutorial will guide you through setting up VS Code for JavaScript development, ensuring a smooth start.
1. Download and Install:
- Head to the official VS Code website: https://code.visualstudio.com/download
- Select the Download for Windows (or your OS) button.
- Once downloaded, run the installer and follow the on-screen instructions. Accept the license agreement and choose your desired installation location.
- Congratulations! VS Code is now installed.
2. Explore the Interface:
- Launch VS Code and familiarize yourself with the layout. The main areas include the editor window, activity bar, explorer panel, and terminal.
- Customize the interface to your preference. You can adjust the themes, fonts, and layouts to create a workspace that feels comfortable and efficient.
3. Install Essential Extensions:
- VS Code’s power lies in its extensive library of extensions. Here are some must-haves for JavaScript development:
- Code Runner: Run your code directly within the editor, making experimentation and debugging a breeze.
- ESLint: Catch errors and stylistic inconsistencies in your code, ensuring cleaner and more maintainable scripts.
- Prettier: Automatically format your code according to best practices, saving you time and effort.
- Debugger: Step through your code line by line, visualize variables, and identify bugs with ease.
4. Connect to Node.js:
- Node.js is a runtime environment that allows you to run JavaScript code outside the browser. Download and install Node.js from https://nodejs.org/en
- Verify the installation by opening the terminal within VS Code and typing
node -v
. You should see the installed Node.js version displayed.
5. Start Coding!:
- Create a new file (File > New > File) and choose JavaScript as the language.
- Write your first JavaScript code! Start with simple examples like printing messages to the console using
console.log()
. - Use Code Runner to instantly test your code and see the results.
- Don’t hesitate to explore the vast online resources and tutorials to learn more about JavaScript and programming concepts.
Bonus Tips:
- Utilize VS Code keyboard shortcuts for efficient navigation and editing.
- Join online communities and forums to connect with other developers and seek help when needed.
- Practice regularly and experiment with different projects to solidify your learning and build a portfolio of your work.
Remember, setting up VS Code is just the beginning. The exciting world of JavaScript awaits you! Dive in, explore, and create your own coding magic.
Additional Resources:
- VS Code Documentation: https://code.visualstudio.com/docs
- JavaScript Tutorials: https://www.freecodecamp.org/
- Node.js Documentation: https://nodejs.org/en
Happy coding!
You’re ready to start
programming with JavaScript. But before you can begin developing projects
with JavaScript, you need to set up
software called VS or Visual Studio Code. VS Code is a code editor that developers use to write
their JavaScript code. By the end of this video, you’ll be able to
install VS Code, Node.js, and the Code Runner extension on your Windows
Operating System. Start a new JavaScript file in VS Code and run the file
using Code Runner extension, and explain what console.log
does in JavaScript. Let’s begin by exploring the VS Code download and
installation process. First, I open a search
engine in my browser and search for the term VS Code
or Visual Studio Code. I click on the first
link which directs me to the official website at
code.visualstudio.com. This link redirects me
to the site’s homepage. On this homepage, I select the Download for Windows button. A message appears on the VS
Code website which states, thanks for downloading
VS Code for Windows. I can then track my download
progress in my browser. Once the file is downloaded, I click the file to begin
the installation process. The license agreement appears. I read through the
agreement and select Next. I then accept the default
installation destination and the Start Menu folder. I also select the following
additional tasks. Create a desktop icon, add open with code action to Windows Explorer
file context menu, add open with code action to Windows Explorer
Directory context menu. Once I’ve selected
these additional tasks, I click “Next”. Now that I have
configured these tasks, I select the Install button. Once installed, I
then check launch Visual Studio Code
and select Finish. My Visual Studio Code program then appears in a new window; on the Get Started page. From here, I click the
bottom-most icon on the very left of the VS Code window to open the extensions panel. Once in the panel, I type Code Runner to search for the Code
Runner extension. I then select and install this extension from
the search results. While the extension installs, I return to my browser
and search for Node.js. I access the file from
the official site at Node js.org and click on the
direct download link, making sure to install
the Windows version. A pop-up appears on screen to track progress
of the download. Once the file has downloaded, I select Open file to open
the Node.js setup wizard. I then select Next and accept
the license agreement. I then click “Install” to begin
the installation process. Once the installation
process has completed, I click the “Finish” button
to close the setup wizard. I then return to VS Code, where the Code Runner
installation process is complete. To confirm that Code
Runner is installed, I can check for the following
message on screen which states this extension
is enabled globally. Just to the right of
the Code Runner tab is a stripe for the files. I double-click this
to open a new file. I then click “Select
Language” and choose JavaScript from
the list of languages. I can also type JS in the search bar to
narrow my results. Next, I close the Code
Runner tab and click on the extension’s icon to toggle
off the extension sidebar. I then click on the
“View” tab and select the Terminal option to open the terminal that
I closed earlier. I need to clear the terminal. I can do this by typing clear
and pressing the Enter key. Next, I hover over the
terminals Output tab. I then click, hold, and drag it to the
right in order to dock it on the right-hand side
of the VS Code window. Now, I close the Terminal again. The Output should remain on the right-hand
side of the screen. I can also adjust the width of the output by dragging the
split to the left or right. Finally, I type some code into the Tab Untitled-1 as follows, console.log, followed
by a pair of parenthesis in which I type
Hello World in single quotes. To run this code, I
click the “Play” icon. I can also use the
shortcut keys, Control Alt N. The words Hello
World appear in my output. Other information also appears, but Hello World is
all I need to focus on for now. That’s it. I’ve successfully set up
VS Code with Code Runner. You now know how to install
Visual Studio or VS Code, Node.js, and the Code Runner extension on your Windows
Operating System. You can also start a
new JavaScript file in VS Code and run the file
using Code Runner extension. You can explain what console.log does in JavaScript. Great work.
Welcome to Programming
Video: Introduction to programming
In this introductory video on coding, the presenter explains the role of programming in the modern world. The audience is guided through the concept that programming involves giving computers a set of instructions using a programming language, with a focus on JavaScript as an example. The narrative uses a relatable scenario featuring Jane’s daily activities, such as buying groceries, tracking heart rate, and ordering flowers, to illustrate how computer programs are integral to our daily lives.
The presenter emphasizes that a computer program is a series of instructions based on rules, written to perform specific tasks under certain circumstances. These instructions are executed by software, also known as programs, running on physical machines called hardware. The video introduces the fundamental idea that programming languages, like JavaScript, act as bridges facilitating communication between computers and people. The distinction between low-level languages (closer to machine language) and high-level languages (like JavaScript) is explained, emphasizing how high-level languages serve as tools to communicate with a computer’s CPU.
The overall message conveyed is that programming is an exciting and pervasive field, touching almost all aspects of the modern world. The audience is encouraged to recognize the significance of programming in daily activities and to embark on a journey to become a part of the world of development.
Welcome to the exciting world of programming, where you’ll gain the power to command computers and bring your ideas to life. This tutorial will be your compass as you navigate the fundamentals of programming, opening doors to countless possibilities!
1. What is Programming?
Imagine giving a robot a set of instructions to follow, like making your morning coffee. Programming is similar! It’s the process of writing instructions that computers can understand and execute. These instructions, written in specific languages like JavaScript, Python, or Java, tell the computer what to do step-by-step.
Think of it like building a bridge between your ideas and the digital world. You write the code, and the computer becomes your tireless worker, following your instructions to create programs, websites, games, and more!
2. Why Learn Programming?
Programming is more than just a technical skill; it’s a powerful tool that empowers you to:
- Solve problems creatively: Approach challenges from a logical perspective and design solutions using code.
- Automate tasks: Write programs to handle repetitive tasks, freeing up your time for more creative endeavors.
- Build amazing things: From websites and mobile apps to games and AI applications, the possibilities are endless!
- Boost your career prospects: Programming skills are highly sought-after in various fields, opening doors to exciting job opportunities.
- Unlock your potential: Develop critical thinking, problem-solving, and analytical skills that benefit all aspects of life.
3. Your First Steps:
Ready to dive in? Here’s your roadmap to get started:
- Choose a programming language: Options like Python, JavaScript, and Java are beginner-friendly, each with its strengths and applications.
- Find learning resources: Online courses, tutorials, coding websites, and bootcamps offer interactive and engaging ways to learn.
- Start with the basics: Learn about variables, data types, operators, control flow (loops and conditionals), and functions, the building blocks of any program.
- Practice makes perfect!: Don’t be afraid to experiment, write code, and make mistakes. The key is to keep practicing and learning from your errors.
- Join the community: Connect with other programmers online or in person to share knowledge, get help, and stay motivated.
4. Remember:
- Programming is a journey, not a destination. Be patient, persistent, and celebrate your progress along the way.
- There are no shortcuts. Learning to code takes time and dedication, but the rewards are worth it!
- Have fun! Programming can be challenging but also incredibly rewarding. Enjoy the process of creating something new and seeing your code come to life.
Bonus Resources:
- FreeCodeCamp: https://www.freecodecamp.org/
- Codecademy: https://www.codecademy.com/catalog
- Khan Academy: https://www.khanacademy.org/computing/computer-programming
- Mozilla Developer Network: https://developer.mozilla.org/
Welcome to the exciting world of programming! With dedication and the right resources, you can unlock your coding potential and create amazing things. So, start your journey today, and let your creativity flow through the power of code!
I hope this tutorial sparks your interest and equips you with the initial steps to embark on your programming adventure. Remember, the online community is vast and supportive, so don’t hesitate to reach out for help or inspiration!
Happy coding!
The zeros and ones of binary code is a low-level language because it's closer to being understood by a CPU. JavaScript on the other hand is a high-level language. This means that it has to be converted to binary code so that a CPU can work with it.
Yes
Yes, that’s correct! As a high-level language, JavaScript does need to be converted to binary code so that a CPU can work with it.
Hello and
welcome to this video about coding. Let’s get started. In this video, you will learn how to interpret the role
of programming in the modern world. Recognize that programming is simply
giving computers a set of instructions to complete using a programming language. And explain how a programming
language like JavaScript helps us tell a computer what to do. Meet Jane,
it’s Janes day off from work and she has three things on her to do list. Buy groceries, track her heart rate while
exercising and buy flowers for her friend. At the grocery store the cashier
needs to use the barcode reader to get the information and prices for
each of the products Jane wants to buy. The cash register adds up these prices,
calculates tax and possible discounts. It then prints out a slip with all
the relevant information listed after Jane pays with a credit card. Later on in the day, Jane uses her smart watch to track
her heartbeats while exercising. The smartwatch is sync to her personal
profile on a social fitness app and she chooses what information about
her activities she discloses. And she also gets to choose
who sees this information. Lastly after finishing her exercise,
Jane orders flowers for a friend online. For many people just like for Jane, our daily activities are intertwined
with computers and computer programs. A computer program is just a series
of instructions based on some rules. These instructions tell a computer what to
do under some specific circumstances and they are written to perform
a specific set of tasks. For example,
when jane is buying groceries, there was a program that could take
the input received from the barcode scanner and
convert it to a price for each item. The cash register program instructed
the printer to take these prices and print them out together with
some other calculations. When Jane was paying with the credit card, the point of sale machine contacted
another program somewhere else. This program took care of
all the bank processing and updated the balance on Jane’s account. Yet more programs were involved in her
smartwatch tracking her heartbeats. Finally, for Jane to be able
to order flowers for a friend, a lot of other programs on many
different machines were involved. These might include satellites or some
other telecommunication computer programs. All these programs are called software and
are in one way or another. Running on physical machines which
are referred to as hardware. Programming is simply the process of
writing the steps a computer needs to take to complete a certain task. To program these instructions,
we use programming languages. A programming language is
sort of like a bridge that we use to facilitate communication
between computers and people. For a computer to understand
a programming language, it needs to save it somewhere
in its random access memory. RAM or on a disk in binary code, which is
represented by a series of zeros and ones. The binary code is a representation
of machine language. That a computer can understand
all of the zeros and ones in binary language
represent electrical switches. Finally, a computer’s
central processing unit, or CPU can comprehend these binary electrical
signals and update itself accordingly. This machine language, with its series
of zeros and ones, is known as a low level language because it’s closer to
being understood by a computer’s CPU. There are also high level languages
such as JavaScript, that needs to be interpreted, that is converted to binary
code that a CPU will be able to work with. So we might think of JavaScript and other high level languages as a tool that
helps us to communicate with the CPU. As you saw with Jane’s example. Computer programs are everywhere. So programming is a very exciting
field that touches almost all aspects of the modern world. And now you’re on your way to becoming
a part of that world as a developer.
Video: Why JavaScript?
JavaScript: The Powerhouse of Interactivity and Web Development
- Ubiquitous Interactivity: JavaScript is the dominant language responsible for dynamic elements like interactive maps, form validation, and real-time updates on websites.
- Client-side King: Since its inception, JavaScript has been the primary way to interact with web pages on the front-end, making it an essential pillar of web development.
- Enduring Popularity: Despite alternatives like VBScript and TypeScript, JavaScript remains one of the most popular programming languages, thanks to backwards compatibility and its deep integration with browsers.
- Ease of Use: JavaScript boasts a low barrier to entry, with browser developer tools offering instant access to experimentation and learning.
- Versatility Unmatched: From plain JavaScript to frameworks like React and Node.js, JavaScript powers every aspect of web development, both client-side and server-side.
- Accessibility and Community: JavaScript is considered approachable for beginners with a large and supportive community offering help and guidance.
- Demand and Opportunity: JavaScript skills are highly sought-after by employers, opening doors to numerous job opportunities and projects.
In essence, JavaScript is the language of the web, powering interactivity, offering ease of use and versatility, and paving the way for a rewarding career in web development.
Bonus: This summary also highlights the unique ecosystem of JavaScript, its role as a stepping stone to other technologies, and the bright future it holds for developers.
In today’s digital landscape, JavaScript reigns supreme. But why? What makes this language so essential for developers and so ubiquitous across the web? Buckle up, as we delve into the compelling reasons why JavaScript should be your programming language of choice!
1. The Web Speaks JavaScript:
Imagine a website frozen in time, devoid of interactivity. That’s the web without JavaScript! This versatile language breathes life into web pages, enabling:
- Dynamic Content: Imagine live updates on news feeds or stock prices. That’s JavaScript in action!
- Interactive Elements: From maps that zoom and pan to forms that validate your input, JavaScript adds a layer of engagement.
- Rich User Experiences: Animations, video players, and interactive games – JavaScript makes them all possible.
2. Unmatched Versatility:
JavaScript isn’t just for the front-end anymore. It’s a chameleon, adapting to various roles:
- Full-Stack Development: Build both the front-end and back-end of web applications with frameworks like Node.js.
- Mobile Apps: Develop cross-platform mobile apps using frameworks like React Native.
- Game Development: From simple browser games to complex 3D experiences, JavaScript is a powerful tool for game creators.
3. Easy to Learn, Easy to Love:
JavaScript is known for its beginner-friendliness. Here’s why:
- Simple Syntax: The language’s structure is straightforward and easy to pick up, even for those with no programming experience.
- Abundant Resources: Countless tutorials, online courses, and communities are available to guide you on your JavaScript journey.
- Immediate Results: Experimenting with JavaScript in your browser’s developer tools provides instant gratification and a sense of accomplishment.
4. A Future-Proof Skill:
JavaScript isn’t just a fad; it’s the future of web development. Here’s why:
- Constant Evolution: The language is constantly evolving, with new features and frameworks emerging to keep developers at the forefront of innovation.
- High Demand: The need for skilled JavaScript developers is ever-growing, making it a valuable asset for your career.
- Open-Source Community: A thriving open-source community drives the language’s development, ensuring its continued relevance and growth.
JavaScript: Your Gateway to the Web
Learning JavaScript isn’t just about acquiring a skill; it’s about opening doors to a world of possibilities. From building interactive websites to developing engaging mobile apps, JavaScript empowers you to shape the digital landscape. So, take the plunge, embrace the challenge, and unlock the exciting world of JavaScript!
Remember, the journey is just as rewarding as the destination. Embrace the learning process, experiment, and have fun with code. The web awaits your creations!
Bonus Resources:
- FreeCodeCamp: https://www.freecodecamp.org/
- Codecademy: https://www.codecademy.com/catalog
- Khan Academy: https://www.khanacademy.org/computing/computer-programming
- Mozilla Developer Network: https://developer.mozilla.org/
Now go forth and code! JavaScript awaits!
You are building a website using JavaScript. On which end of the site will JavaScript add interactivity to?
Front-end
Yes, JavaScript adds interactivity to the front-end, or client-side, of a webpage.
In the last few hours or
maybe even in the last few minutes, you’ve probably interacted with web pages
to do things like watch videos, look for locations on maps, or
interact with your social media feeds. In fact you’re doing it
right now with this course. But what makes this
interactivity possible? The programming language JavaScript. Let’s find out a bit more about
the benefits of JavaScript and its importance to developers. JavaScript is a language that builds
interactivity into web pages. It is literally the language of the web. Almost every website runs
JavaScript in some form or another. The reason for this is the fact that
since its very inception In 1995, JavaScript has been the main way
to interact with web pages on the client side, the front and
side of websites and web applications. Using JavaScript updates are displayed
in real time on our devices. Some common examples include interactive
maps and client side form validation. Over the years, there have been
some alternatives to JavaScript, such as VBScript and
more recently TypeScript. But even typescript compiles down to
JavaScript so browsers can understand it. Since JavaScript is one of the most widely
available and frequently used methods for interacting with the browser
on the client side, the language became immensely popular. In fact, developer surveys often show that
JavaScript remains one of the most popular programming languages today. So what is it that makes JavaScript so
integral to modern browsers. JavaScript is currently
the only computer language that allows us to directly interact with our
web pages dynamically on the client. It’s baked into the browser. Its enduring popularity is down to the
rules of backwards compatibility, which states that all websites that were built
in the past still need to work today. So removing JavaScript from the browser
would effectively render millions of websites completely useless. This means that JavaScript is in the
unique position of being one of several central pillars of web development. You’ve just discovered the importance
of JavaScript to web development. JavaScript unique ecosystem is one of
the main reasons for its popularity. Simply put, browsers speak JavaScript. But there are a few other important
reasons why we should embrace JavaScript. One of the main reasons
that developers use JavaScript is because of
how easy it is to use. There are many programming languages where
a newcomer needs to do a substantial amount of prep work to even get set up and
ready to learn. However, with JavaScript it’s as simple as
opening the browser’s developer tools and navigating to the console tab because
every browser has a JavaScript engine built in and you can interact
with it using the console. There are still a few small steps
required to get started with JavaScript. These include installing a code editor and possibly setting up some other
things such as Node.js and NPM. But initially as a beginner, it’s enough to just open the developer
tools on your web browser. Another reason to learn and use
JavaScript is because as we saw earlier, it’s everywhere. JavaScript is used in almost
every website there is. It’s used on the client side of
sites as plain JavaScript also known as vanilla JavaScript. It fuels a myriad of JavaScript
frameworks such as React, Vue, and D3 and it’s also used on the server
as Node.js and more recently Deno. Another reason why people often choose
JavaScript is that it’s considered one of the more accessible
programming languages. It also has a wide development
community to offer help and guidance. This is especially true when it’s
compared to other languages. There are many languages that for a variety of reasons would be very
challenging to begin programming with. But because it’s so approachable,
JavaScript can be a great way for new developers to jump into programming. So besides being a useful
skill on its own, JavaScript can also be a stepping stone
to other languages and technologies. Finally, one more reason to learn
JavaScript is because JavaScript skills are in demand. Countless job postings appear for
JavaScript developers every day and these will keep coming for
the foreseeable future. So next time you ask why choose JavaScript
remember that it’s the foundation of technology of everything you do
online with a huge variety of uses. Plus it’s easy to get started with and
once you’re up and running there’s lots of job offers and
projects open to you. Best of luck with your JavaScript journey.
Video: Programming in JavaScript
- JavaScript is ubiquitous: It powers various functionalities across browsers, servers, mobile apps, and even the Internet of Things.
- Diversity breeds complexity: Different use cases led to diverse implementations and browser inconsistencies, causing compatibility headaches for developers.
- jQuery to the rescue: This library provided universal JavaScript code, solving compatibility issues and becoming the dominant library for over a decade.
- Evolution demands new solutions: As web development evolved, new problems emerged, leading to frameworks like React to address issues with complex websites.
- Legacy code lingers: While frameworks like jQuery may not be used for new projects, they remain prevalent in older websites.
- Focus on the foundation: Mastering plain JavaScript is crucial before diving into frameworks like React, as it provides the necessary understanding for building upon.
Key takeaway: While various JavaScript technologies exist, understanding the core language is essential before exploring specific frameworks.
This tutorial is your gateway to exploring the dynamic and powerful world of JavaScript programming. Get ready to unlock your coding potential and build interactive web pages, mobile apps, and more!
1. What is JavaScript?
JavaScript is a versatile programming language used to add interactivity and functionality to web pages. It’s the language behind the dynamic elements you see online, like animations, pop-ups, and interactive forms. But JavaScript isn’t just for the web anymore! It’s also used to build mobile apps, server-side applications, and even power devices in the Internet of Things (IoT).
2. Why Learn JavaScript?
There are countless reasons to learn JavaScript:
- High Demand: JavaScript skills are highly sought-after in the job market. Companies of all sizes need developers who can build and maintain web applications and more.
- Versatility: Once you know JavaScript, you can explore various domains, from web development to mobile app development and even game programming.
- Relatively Easy to Learn: Compared to some other languages, JavaScript has a beginner-friendly syntax and a plethora of learning resources available.
- Fun and Engaging: Learning and coding with JavaScript can be a rewarding and creative experience. Seeing your code come to life and interact with users is truly satisfying.
3. Getting Started:
To embark on your JavaScript journey, you’ll need the following:
- Text Editor: Choose a code editor like Visual Studio Code, Sublime Text, or Atom. These editors provide syntax highlighting, autocompletion, and debugging tools to make your coding experience smoother.
- Web Browser: Your favorite browser, like Chrome, Firefox, or Safari, will be your playground for testing your JavaScript code.
- Learning Resources: There are countless online tutorials, courses, and books available to guide you through your learning journey. Check out platforms like FreeCodeCamp, Codecademy, Coursera, or Khan Academy for interactive learning experiences.
4. The Basics:
Let’s dive into the fundamental building blocks of JavaScript:
- Variables: Store data like numbers, text, and booleans (true/false) in variables.
- Data Types: Understand different data types like strings, numbers, arrays, and objects to represent various kinds of information.
- Operators: Use mathematical and logical operators to perform calculations and make decisions in your code.
- Control Flow: Learn how to control the flow of your program using conditional statements like
if
,else
, and loops likefor
andwhile
. - Functions: Define reusable blocks of code that can be called upon multiple times.
5. Building Interactive Web Pages:
Now that you’ve mastered the basics, let’s take your learning to the next level by adding interactivity to web pages:
- DOM Manipulation: Learn how to access and modify HTML elements on your web page using JavaScript code.
- Events: Capture user interactions like clicking, scrolling, and typing to trigger JavaScript code and create dynamic responses.
- APIs: Explore APIs (Application Programming Interfaces) to connect your JavaScript code with external services and functionalities.
6. Resources and Community:
Remember, learning is a continuous process! Here are some resources to keep you motivated and connected:
- Online communities: Join online forums and communities like Stack Overflow or Reddit to ask questions, share your progress, and learn from others.
- Open-source projects: Explore open-source projects on GitHub to see how other developers are using JavaScript and contribute your skills.
- Practice and build: Don’t be afraid to experiment and build your own projects. Start small and gradually increase the complexity as you gain confidence.
JavaScript is a powerful language with endless possibilities. With dedication and the right resources, you can unlock your coding potential and create amazing things!
This is just a starting point for your JavaScript adventure. As you progress, you’ll delve deeper into advanced concepts and explore the vast ecosystem of frameworks and libraries. Remember, the key is to stay curious, keep practicing, and enjoy the journey!
Happy coding!
JavaScript is integral to our everyday online experiences. Which of the following statements are true? Choose all that apply.
JavaScript is used to power websites.
That’s correct! JavaScript is after all often called the language of the web.
Using JavaScript and React Native developers can create mobile apps.
That’s correct! JavaScript isn’t limited to only being used in browsers. Developers can also create apps using it in conjunction with React Native.
JavaScript can provide a native feel to apps.
That’s correct! Using JavaScript developers can create an original user experience.
Javascript is used in many
scenarios, for example, in the browser to help add various behaviors
and interactivity, like adding an item to a shopping cart when
you click a button. On the server, it can be
used to power up websites, communicate with databases, and provide a native
fields to web apps. It’s used to build mobile
apps using technologies like React Native and it’s used to program devices known as
the Internet of Things. In a nutshell, JavaScript
is everywhere. This means that there are
many different use cases for JavaScript and with
these different use cases, come different implementations, each geared towards solving
a particular problem. For example, in the early 2000s, different companies
built Internet browsers and were referred to
as browser vendors. However, with different
browsers came different behaviors with various discrepancies
between other browsers. This resulted in developers
sometimes having to write separate JavaScript code
for different browsers. This wasn’t the best use
of developer time and could lead to a frustrating
experience for end-users. Out of this frustration, several projects appeared trying to solve this
compatibility problem. One such project
managed to solve these issues and it was
a library named jQuery. Using this library, all a
developer needed was to import jQuery and write
code using its features. This code would then work
across all browsers. At the time, it was like magic, as it was such a
great solution to the problem of
incompatibility and jQuery became the most
popular JavaScript library for well over a decade. However, as the web and the
way we code kept evolving, new problems appeared,
and soon enough, new solutions to those
problems needed to be built. Once such solution was React, which came out in
2011 and it had a considerable
effect on the way we think about websites
and how we build them. React, solved many of the issues associated
with creating, updating and maintaining
complex websites. Soon, many other technologies appeared attempting
to do the same. These include
Knockout, Backbone, Angular, Ember, Vue, Alpine, and others. With millions of
websites containing JavaScript code from different
versions and libraries, there is a lot of old code. This is known as a legacy code. While you probably won’t use jQuery to build a
modern website today, you might still
come across it in a project that is still
actively running. But don’t worry, sometimes beginners think they
have to learn or even master all the
different technologies associated with JavaScript. However, that’s not
really necessary. To be a well-rounded developer, you need to learn and
master the basics of plain JavaScript
without the frameworks. Once you have this foundation, the pathway will become easier for you to
learn a framework built on top of
JavaScript, such as React.
Reading: Writing your first Javascript code
Reading
In this reading, you’ll learn about comments in JavaScript. Additionally, you’ll learn about the semi-colon in JavaScript: what it does and why it is used. You will then download a browser if you don’t have one installed and run your first piece of JavaScript using the Console.
Comments in JavaScript
I’ve chosen comments as the starting point for two reasons:
- Their syntax – the way comments are written is easy to understand.
- Writing comments can empower you as a developer.
First, I’ll explain the syntax, and after that, I’ll discuss why being able to write comments is so empowering.
Comments in JavaScript: the syntax
There are two varieties of comments in JavaScript:
- Single-line comments
- Multi-line comments
A single-line comment is created when you add two forward-slash characters one after the other, without spaces.
// this is a comment!
Anything that follows a single-line comment in JavaScript is ignored by the browser.
This means that, essentially, you can write any kind of text, code, characters, emojis, whatever – and the browser will ignore it.
A multi-line comment, as its name says, spans for several lines of code and is created with a forward slash and a star. For example:
/*
this
is
a
multi-line
comment
*/
You can also use the multi-line comment syntax on a single line of code, as follows:
/* this is a multi-line comment on a single line */
Why writing comments is empowering
In this course, it is assumed that you’ve never written a single line of JavaScript code.
With this assumption in mind, consider the effects of what you’ve just learned, that is, the effects of learning how to write comments in JavaScript:
- You can now freely express your ideas about any code that you write.
- You can add comments to any code that already exists.
- Those comments can be intended for your future self, or for colleagues on your development team.
So, comments are empowering because they facilitate communication with your future self or with your team members, allowing you to ask questions about the code, mark the code as “to do”, or as “to improve”, or just simply explain what a given piece of code does.
Additionally, you can even comment out some working code in a JavaScript file – to prevent it from running.
Effectively, comments allow you to “switch off” pieces of JavaScript code.
There can be many reasons for that:
- Trying to understand how a given piece of code works.
- Testing different solutions to a coding problem – while not having to delete existing code.
- Debugging – trying to pin-point why your code is broken or behaving unprediticably.
The semi-colon in JavaScript
In the English language, the fullstop or period – the . character – is used to separate thoughts into sentences.
By clearly separating thoughts with the fullstop, you avoid being misunderstood.
In JavaScript, the semi-colon – the ; character – has a similar purpose: it is used to clearly delimit parts of the code from some other parts of the code.
Automatic Semi-Colon Insertion (ASI)
Interestingly, the browser has a feature known as “Automatic Semi-colon Insertion” – meaning, it does a pretty good job of “filling in the blanks” in case there is a missing semi-colon where there should be one.
Effectively, what that means for developers is that most of the time, it makes no difference if a semi-colon is added or not, since the browser is likely to figure it out anyway.
That’s why some developers say that you shouldn’t bother with adding semi-colons at all.
However, other developers argue that it’s better to use it wherever it’s needed – for the sake of clarity.
The truth is that most of the time, you can think of adding semi-colons in JavaScript as optional – and somewhat of a stylistic preference.
A note on using the console in the developer tools in your browser
As already mentioned earlier on in this course, one of the reasons why JavaScript is so popular is because it’s so approachable.
To get started with JavaScript, all you need is a browser. In this course I’ll be using Google Chrome.
Once you’ve installed the browser and run it, right-click on the currently active web page and click the Inspect command on the right-click contextual menu.
This will open the Developer Tools and then you can click on the Console tab to open the console, or alternatively, pressing the ESC key will toggle on and off the console regardless of the currently active Developer Tools panel.
You can type any JavaScript command you like into the DevTools console.
If you need to type multiple lines of code before you run them, make sure to press the SHIFT + ENTER shortcut key to get onto the next line.
Notice the distinction between pressing the ENTER key to run the JavaScript code you’ve typed, versus pressing the SHIFT + ENTER shortcut to move onto the next line of code (rather than running the code you’ve already typed up).
This is all that you need to get started writing JavaScript code!
In the upcoming lessons, feel free to follow along in either of two ways:
- Using the VS Code editor and the Code Runner extension as previously described
- Using the Chrome browser itself, and running the code inside the DevTools console as described in this reading
Output a greeting into the console
Now that you know how to get to the Developer Tools’ Console tab, let’s now use it to run your first piece of real JavaScript code.
In Chrome, with the Developer Tools open, click into the empty space in the console tab, just to the right of the blue > character. You should see a blinking vertical line (also referred to as “the cursor”). The cursor indicates that you can type into the console.
If you type valid JavaScript code, it will be executed, meaning: it will be processed and it might result in some kind of output.
You’ll now use the console.log function to output the words “Hello, World”.
To do so, type the following command into the console:
console.log("Hello, World");
If you’ve done everything as instructed, the words “Hello, World” should be output in the console.
Here’s another, more complex command, to show you that the console.log command comes with a number of tricks.
For example, did you know that you can style the output in the console?
In this code snippet, there are a few additions: the font size is different and the color is blue:
console.log("%cHello, World", "color: blue; font-size: 40px");
If you copy-paste this piece of code, or perhaps, simply type it into the console, once you press the ENTER key to run it, you’ll get the words “Hello, World” output to the console. This time, however, the color of the letters will be blue, and the font size will be 40px. So, you’ve just learned a nice trick with the console.
If you add the %c right after the “ character, you can then style the console output by adding the , character after the second “, and then, inside another pair of “ and “ characters, use valid CSS code to style the words you want to output in the console.
The reason for showing you this little trick was to hopefully get you motivated to practice writing various words into the console.log command, and to use your CSS skills to change the styling of these words in the console output. That way, you might find it fun to practice this newly acquired skill – and learning and fun always go nicely together.
Output multiple words into the console
To output multiple words into the console, you can join them using the + character, formally known as the “concatenation operator” when we’re joining pieces of text, or the “addition operator”, for performing the mathematical operation of adding two numbers.
Here is an example of joining three separate pieces of text: console.log(“Hello ” + “there, ” + “World”). The output of this command will be: Hello there, World.
Here is an example of outputting three separate pieces of text using the , character instead:
console.log(“Hello “, “there, “, “World”)
The output of this command will still be: Hello there, World.
Video: Variables
This video dives into the concept of variables in JavaScript, highlighting their role in building interactive programs. Here are the key takeaways:
1. Blank Canvas: A new JavaScript program is like an empty world, ready for the programmer to define its structure and functionalities using code.
2. Variables as Building Blocks: Variables are crucial tools for storing and reusing data within this world. They act as containers for values like names, messages, or numbers.
3. Declaring vs. Assigning: Declaring a variable with var
establishes its existence, while assigning a value with =
fills it with data.
4. Reusing Data with Variables: Variables save you from repeatedly typing the same data, promoting code efficiency and flexibility.
5. Dynamic Output: By using variables in conjunction with methods like console.log
, you can dynamically generate different outputs based on the stored values.
6. Reassigning Values: Variables are not static; their values can be changed throughout the program, leading to diverse outcomes with the same code.
7. Power of Variables: This dynamic nature of variables empowers you to build versatile programs that adapt to different scenarios and data.
Bonus: The video mentions further learning resources for those who want to delve deeper into the world of variables and JavaScript programming.
Remember, mastering variables is a foundational step in your JavaScript journey. As you progress, you’ll discover more advanced techniques and tools to build even more complex and interactive programs.
Welcome, adventurers! Prepare to embark on a quest into the fantastical realm of JavaScript, where variables are your trusty companions. But before we set off, let’s equip ourselves with the knowledge to wield them like seasoned code warriors!
What are Variables?
Think of a variable as a magical chest that holds valuable treasures. In our JavaScript world, these treasures are pieces of data, like numbers, text, or even booleans (true or false). You can give them names and call upon them at any time, making your code flexible and powerful.
Creating Your Treasure Chest:
To create a variable, we use the var
keyword followed by the chosen name. Remember, names should be descriptive and clear, like playerScore
, monsterName
, or isOpen
.
Filling the Chest with Treasure:
Now comes the fun part! Use the =
symbol (like an assignment spell) to fill your chest with data. For example, var playerScore = 100
assigns the value 100 to the variable playerScore
. You can store anything from “Mighty Warrior” in heroName
to true in isBossDefeated
.
Unleashing the Power:
Once filled, your variables become versatile tools. You can use them in calculations, control program flow, display information, and much more! Imagine shouting “playerScore + 10” to increase your score after defeating a foe!
Advanced Techniques:
As you gain experience, you’ll unlock even more powerful ways to use variables. You can:
- Combine data: Use
+
to create “Giant Spider” fromgiant
andspider
. - Compare treasures: Check if
playerHealth > monsterAttack
to see if you can withstand the blow. - Change values: Cast the “updateLevel” spell to modify
playerLevel
. - Use different types of chests: Explore
let
andconst
for more control over your data.
Remember:
- Choose clear names for your variables to avoid confusion.
- Use the right data type for each treasure (numbers, text, booleans).
- Don’t overload your chests – keep them organized and focused.
- Practice makes perfect! Experiment and have fun with your variable magic.
Bonus Quest:
Can you create a JavaScript adventure where you use variables to track your progress, solve puzzles, and defeat enemies? Share your code and challenge your fellow adventurers!
With these tips, you’re well on your way to mastering the art of variables in JavaScript. Remember, the power lies in your imagination and your code! So, go forth and build your own fantastical worlds with the magic of variables!
I hope this tutorial sparks your curiosity and guides you on your JavaScript journey. Please let me know if you have any questions – I’m always happy to help fellow adventurers!
In JavaScript you can declare a variable with the keyword var. Which one of the following statements about var is correct?
Var allows you to save a variable so that you can re-use it in future.
Yes, that’s correct! Var makes your life as a programmer easier by allowing you to re-use a variable multiple times.
When you start programming
in JavaScript, it helps to think of an empty JavaScript program as the first level
of a sandbox game. The world is still empty, but there’s some underlying
structure to it to build on. That structure needs to
be there so that you can write custom JavaScript
code in the first place. However, besides the
underlying structure, a new JavaScript program is like a blank slate
for you to build on. It’s up to you, the
programmer using JavaScript, to say, let’s build this world. An important part
of this process is knowing how to use variables. In this video, you
will learn how to identify what a variable
is and why you need it, distinguish between
variable declaration and variable assignment
and describe how to get a variable’s value
and reassign it. Let me demonstrate this now, using some code to
assign a value to a variable and output
it to the console. Right now, I have the Developer Tools panel
open in my web browser. You can access this by pressing ”F12” on Windows and Linux, or command option “I” on Mac then I select
the console tab. This works with any browser, and for this example, I’m using Google Chrome. Now I want to give JavaScript some idea of what
I want to build, and I start by adding
a person’s name. I do this by typing John
in double quotation marks. JavaScript receives this
person’s name and accepts it. There are no errors. This means I’ve given
it some valid data, something that JavaScript
can work with. Now let’s say that I want JavaScript to say, “Hello John”. In other words, I want it
to use the name that I gave JavaScript and I want
it to greet the person. But how do I do it? If I type, “Hello John”, I’m just typing the
whole thing myself. I really want JavaScript to
use the name I provided, so I don’t have to
keep retyping it. This is where variables come in. By using a variable, I can save the name John, so that I can reuse
it in the future. To save this name in a variable, I’ll start with
the keyword, var, and use it to signal
to JavaScript that I’m giving it a value
that I wanted to reuse. To declare a variable, I type the keyword, var. Now, I need to declare a fact about this world
that I’m building, so I type, person semicolon
and press “Enter”. Great. I’ve just declared
my variable, person. I’ve given JavaScript one fact about the world
that I’m building. The fact that there is a
value that I’d like to reuse and that this value is accessible
using the word person. Thus I have completed the
variable declaration. However, I still haven’t given a name to the
person variable. In programming
jargon, I’d say that the person variable hasn’t
been assigned a value yet. The person variable
is still undefined. In other words, for the person variable to hold
the value of John, I need to assign the value of John to the person variable. To do this, I’ll use the assignment operator,
the equals sign. Operators perform
certain operations, and the assignment
operator’s purpose is to take the value that is on its right and put it
into what it’s on its left. To assign the name John
to the variable person, I type var person equals
John in-between quotes. I’ve taken the value
John and assigned it to the person variable using
the assignment operator. To confirm that this
is really the case, let me inspect the
contents of the person variable by typing,
person semicolon. It returns John as the result. Now that I have this
value in a variable, I no longer have to type John every time I
want to use it. I can have JavaScript
output the text, “Hello John” to the console by using the built-in
console.log method. This is a common approach to outputting values in JavaScript. Notice that the browser is
intelligently trying to guess what programming
statement I want as I type. Don’t worry about this now. I just want you
to concentrate on variables and the
console.log method. The console.log
method can accept one or more values
separated by commas. So, I type console.log, open parenthesis then I
type ”Hello” in quotes, comma, person for the variable and then
close parenthesis. Notice that “Hello John” is
now logged to the console. This is an example of combining static text with a
dynamic variable where the value can change. But why stop here? Why not save the greeting
in a variable too? Let’s create another variable
and call it, greeting, and assign this new
variable the value, hello, in quotation marks. Now, when I use the console.log method
with both variables, greeting and person, the words or the values
of these variables, ”Hello John” are
logged to the console. Finally, let me show you why
variables are so useful. Now that I have the person
and the greeting variables, I can reassign them, replacing their stored values. For example, I can change the value of the
variable from hello to hi by typing greeting
equals hi in quotation marks. Similarly, I can change the value of the
variable person from John to James by
doing the same thing. I type person for
the variable then equals and finally James
in quotation marks. Now, the value of the
variable, greeting, is hi, and the value
of the variable, person, is James. Notice that now I haven’t
used the var keyword when I reassigned the values to the variables that
I created earlier. That’s because JavaScript
already knows that these variables exist in the
world that I’m building. But the variables don’t have to be static and unchangeable. That would be a
pretty boring world. Now, I run the exact same
piece of code as before by typing console.log and
the name of the variables. Notice that I’ll get a completely different result logged to the console, hi James. This is very important
because it allows me to use the same code
and get different results. This is the power of variables. If you want to find out more, there is an additional reading
at the end of this lesson. Congratulations. You now know how to create
a variable in JavaScript. Variables allow us to make the exact same code
produce different results, making our programs versatile. That’s it for this
video on variables. Now that you’ve had
some insight into how JavaScript
world-building works, I hope you are excited to learn about more than just variables.
Reading: Exercise: Declaring variables
Reading
In this exercise, you will practice declaring variables.
To check the output of your code, please enter it into the text box provided and click the “Run” button. This will execute the code and display the resulting output.
Tasks
- Declare a new variable named petDog and give it the name Rex.
- Declare a new variable named petCat and give it the name Pepper.
- Console.log the petDog variable.
- Console.log the petCat variable.
- Console.log the text “My pet dog’s name is: “ and the petDog variable.
- Console.log the text “My pet cat’s name is: “ and the petCat variable.
- Declare another variable and name it catSound. Assign the string of “purr” to it.
- Declare another variable and name it dogSound. Assign the string of “woof” to it.
- Console.log the variable petDog, then the string “says”, then the variable dogSound.
- Console.log the variable petCat, then the string “says”, then the variable catSound.
- Reassign the value stored in catSound to the string “meow”.
- Console.log the variable petCat, then the string “now says”, then the variable catSound.
Make sure to output all your variables. Feel free to play.
var petDog = "Rex"
var petCat = "Pepper"
console.log(petDog)
console.log(petCat)
console.log("My pet dog's name is:", petDog)
console.log("My pet cat's name is:", petCat)
var catSound = "purr"
var dogSound = "woof"
console.log(petDog,"says",dogSound)
console.log(petCat,"says",catSound)
var catSound ="meow"
console.log(petCat,"now says",catSound)
Rex
Pepper
My pet dog's name is: Rex
My pet cat's name is: Pepper
Rex says woof
Pepper says purr
Pepper now says meow
Reading: Declaring variables (solutions)
Reading
Here are the solutions to the previous exercise, which was to practice declaring variables.
Please note: The solutions presented here use single quotes and double quotes interchangeably to delimit pieces of text. This is done on purpose to illustrate that both ways of representing text are possible and acceptable so that you are aware of it.
Task 1 solution to: Declare a new variable named petDog and give it the name Rex.
var petDog = 'Rex';
Task 2 solution to: Declare a new variable named petCat and give it the name Pepper.
var petCat = 'Pepper';
Task 3 solution to: Console log the petDog variable.
var petDog = 'Rex'; // Task 1 solution
console.log(petDog);
Rex
Task 4 solution to: Console log the petCat variable.
var petCat = 'Pepper'; // Task 2 solution
console.log(petCat);
Pepper
Task 5 solution to: Console.log the string “My pet dog’s name is: “ and the petDog variable.
var petDog = 'Rex'; // Task 1 solution
console.log("My pet dog's name is: " + petDog);
My pet dog's name is: Rex
Please note that in this specific example, because the text in line 2 contains a single quote within it, you should use double quotes to surround the whole piece of text. Otherwise, JavaScript will return an error. We will cover this issue in more detail later.
Task 6 solution to: Console.log the string “My pet cat’s name is: “ and the petCat variable.
var petCat = 'Pepper'; // Task 2 solution
console.log("My pet cat's name is: " + petCat);
My pet cat's name is: Pepper
Please note that in this specific example, because the text in line 2 contains a single quote within it, you should use double quotes to surround the whole piece of text. Otherwise, JavaScript will return an error. We will cover this issue in more detail later.
Task 7 solution to: Declare another variable and name it catSound. Assign the string of “purr” to it.
var catSound = "purr";
Task 8 solution to: Declare another variable and name it dogSound. Assign the string of “woof” to it.
var dogSound = "woof";
Task 9 solution to: Console.log the variable petDog, then the string “says”, then the variable dogSound.
var petDog = 'Rex'; // Task 1 solution
var dogSound = "woof"; // Task 8 solution
console.log(petDog, "says", dogSound);
Rex says woof
Task 10 solution to: Console.log the variable petCat, then the string “says”, then the variable catSound.
var petCat = 'Pepper'; // Task 2 solution
var catSound = "purr"; // Task 7 solution
console.log(petCat, "says", catSound);
Pepper says purr
Task 11 solution to: Reassign the value stored in catSound to the string “meow”.
var catSound = "purr"; // Task 7 solution
catSound = "meow";
Task 12 solution to: Console.log the variable petCat, then the string “now says”, then the variable catSound.
var petCat = 'Pepper'; // Task 2 solution
var catSound = "meow"; // Task 11 solution
console.log(petCat, "now says", catSound);
Pepper now says meow
Video: Data types
This video delves into the fundamental building blocks of JavaScript: its data types. Understanding these types is crucial for efficient and effective coding.
Key Takeaways:
- Seven Primitive Types: JavaScript offers seven core data types for storing diverse information:
- String: Textual data, like names or descriptions.
- Number: Numerical values for calculations and representations.
- Boolean: True or false flags for decision-making.
- Null: Represents the absence of a value.
- Undefined: Denotes a variable lacking an assigned value.
- BigInt: Accommodates extremely large numbers beyond typical ranges.
- Symbol: Generates unique identifiers for object property distinction.
- Data Type Selection: Choosing the appropriate type is vital for optimal code performance and clarity.
- Mismatching types can lead to errors and hinder functionality.
- For instance, storing price as a string prevents calculations.
Benefits of Understanding Data Types:
- Improved Code Efficiency: Utilizing the correct type optimizes memory usage and processing.
- Enhanced Code Readability: Clear type usage makes code easier to understand and maintain.
- Reduced Errors: Matching data types to their intended purposes minimizes coding mistakes.
Overall: Mastering JavaScript data types empowers developers to write efficient, robust, and maintainable code. By understanding their specific use cases and implications, you can elevate your coding skills and build high-quality applications.
Please note: This summary avoids overly informal language and focuses on key concepts and their professional implications.
Video: Operators
Focus: Understanding and using assignment, logical, and comparison operators in Javascript.
Key Points:
- Assignment operators:
+
,-
,*
,/
for basic arithmetic.- Used to assign values to variables and perform calculations.
- Comparison operators:
>
,<
,>=
,<=
,==
(equal) for comparing values.- Return
true
orfalse
based on the comparison result.
- Logical operators:
&&
(and),||
(or),!
(not) for combining comparisons.- Used to control program flow based on multiple conditions.
- Demonstration:
- Code examples using operators in VS Code.
- Output showing the results of different operations.
Takeaways:
- Operators are essential for manipulating data and controlling program flow.
- Understanding different operators and their uses is crucial for effective Javascript programming.
- Practice with code examples to solidify your understanding.
Bonus:
- Explore more advanced operators like bitwise and string operators.
- Learn about operator precedence and how it affects expression evaluation.
Remember: Mastering operators is a key step in your Javascript coding journey!
Welcome, coding adventurers, to the exciting world of Javascript operators! Think of them as your trusty tools, ready to shape and manipulate data like a master sculptor. In this tutorial, we’ll explore the essential operators that power your Javascript programs.
First things first, what are operators?
They’re the tiny heroes behind the scenes, performing calculations, comparisons, and controlling the flow of your code. Just like a chef uses different utensils for various tasks, Javascript has operators for every need!
Let’s meet the basic crew:
- Arithmetic Operators: These are your math buddies, adding, subtracting, multiplying, and dividing numbers with ease. Think of them as your calculator in code form!
- Comparison Operators: Ever wondered if two numbers are friends or foes? These operators compare values like
>
,<
,==
, and more, returning true or false based on their relationship. - Logical Operators: Need to make decisions in your code? These operators combine comparisons like
&&
(and),||
(or), and!
(not), helping you choose the right path for your program. - Assignment Operators: These are the movers and shakers, assigning values to variables like
=
or using shortcuts like+=
for quick updates. Think of them as giving your variables a makeover!
But wait, there’s more!
Javascript has a whole toolbox of operators waiting to be discovered, like string manipulation, bitwise operations, and even ones for working with dates and times. As you progress, you’ll unlock these advanced tools and become a coding master!
Remember, safety first!
Just like any powerful tool, operators can be misused. Always be mindful of:
- Data types: Don’t try to add apples and oranges (unless you’re coding a fruit salad simulator!). Use operators with compatible data types for accurate results.
- Precedence: Operators have priorities, like multiplication before addition. Pay attention to the order of operations to avoid unexpected outcomes.
- Clarity: Use clear and concise code with proper spacing and comments to avoid confusion and errors.
Ready to put your operator skills to the test?
Here are some fun ways to practice:
- Write simple calculations using arithmetic operators.
- Compare movie ratings using comparison operators.
- Create a quiz with logical operators to check user answers.
- Experiment with different operators and see what they do!
Remember, learning operators is a journey, not a destination. Embrace the exploration, experiment, and most importantly, have fun coding!
Bonus tip: Check out online resources and tutorials for more advanced operator tricks and techniques. The Javascript community is always here to help you on your coding adventures!
So, grab your operator toolkit and start crafting your Javascript masterpieces. With a little practice, you’ll be a coding whiz in no time!
Where do you think the
name operators come from? Does it have
something to do with an operation of some sort? Well, the answer is yes. Operators are used to perform operations on
variables and values. An operator is
used to manipulate individual data items
and return a result. For example, you may
already be familiar with the assignment operator to
assign a value to a variable. You use assignment operators for simple and complex calculations. They provide us with similar options to
those on a calculator. In this video, you will
learn about assignment and logical operators and how
to use them in JavaScript. First, let’s start with the assignment
operators which you can use to perform
simple arithmetic. For example, to add two numbers, you can use the
addition operator, which is represented
by the plus symbol. If you want to subtract values, use the minus operator, which is represented
by the hyphen symbol. If you want to perform
division, for example, 35 divided by 5, use the division operator, which is represented
by the forward slash. Finally, to multiply numbers, use the multiplication operator, which is represented
by the star symbol. In addition to
assignment operators, you can also use
comparison operators, which compares and returns a logical value based on
whether the comparison is true. For example, you can compare numbers to check if
they are greater than, less than, equal or not
equal to each other. You will learn more about
the various assignment and comparison operators
later in this course. But for now, let me tell you
about logical operators. Logical operators are
used in JavaScript to determine if something
is true or false. For example, the logical
operator named end, which you can use to check the two or more
conditions are true. Imagine you had a
variable named A and you wanted to check
that its value is greater than five
and less than 10. For this to be satisfied, both statements must be true. Alternatively, there is
the operator named R, which checks for at least one of the statements
to be true. For example, A is
greater than five, RA is greater than 10. Finally, you can use
the logical operator, NOT, which returns a false
value if the result is true. Operators are used to control the flow of a program that
meets certain criteria. Now let me demonstrate
how to use JavaScript, math and logical operators. I’ve opened VS Code here. Now, let me demonstrate
how you can use arithmetic and comparison
operators in JavaScript. Recall that comments are used to specify which lines
JavaScript should ignore. As you learned earlier, you can put almost
anything inside comments. Notice I have two
multi-line comments. The first one lists some
arithmetic operators, and the second one lists
some comparison operators. I also have several
single-line comments. You already learned that JavaScript completely
ignores comments, and here’s the proof. I click on the Run code icon. Notice that the output in the
right panel will not show any values other than the expected additional info
on the code that was run. Let me clear that for now
and show you how to work with some arithmetic and
comparison operators. I’m going to uncomment all single-line comments
from lines 14-21, so that you can focus on each of these console logs separately. This will then allow
me to demonstrate how each of these
operators behaves. Let me delete the two
forward slashes on line 14 and rerun this file. Notice I get the value of four
outputted to the console, resulting from adding
the values 2 plus 2. Let me clear the console, comment line 14 and
uncomment line 15. This is an example of adding multiple numbers using
the plus operator. Notice when I run this, I get the output of 15. Let’s do another one using the subtraction operator
to subtract 18 from 20. If I run this, I get the
expected output of two. Next is multiplication, which is represented by
the asterisk symbol. Here I will console
dot log the values of 2 times 3 to get
the value of six. On line 18, I use the forward slash symbol for the division
of eight by one. Notice when I run this, a value of eight is
outputted, success. That’s it for performing simple
arithmetic in JavaScript. Let me clear my screen again. Now I want to demonstrate how to work with comparison operators. Notice on line 19, I use the greater than symbol to check if three is
greater than two, run it and indeed it is, I get an output of true. On line 20 I use
the greater than symbol to check if two
is greater than three. Since it’s not, I receive
an output of false. These words true and false are special kinds of values
used in JavaScript. Don’t worry too much
about them now, as you will learn more
about this later. For now, I just want you to focus on the final line of code. This checks if one value
is equal to another value. It’s important to remember
that you need to use the equals symbol twice for this comparison
operator to be valid. This is because the
single equal symbol is used for the
assignment operator, like when you assign a
value to a variable. I would expect the value
of 10 to be equal to 10. Let’s run it to
find out and it is. Notice a value of true is
outputted to the console. Congratulations, you have now learned how to work with
operators in JavaScript. This is a must-have skill
in your development toolkit as they are used in many areas of programming. Great work.
JavaScript, like any other programming language, needs a way to organize and store information. This is where data types come in. They’re the building blocks of your code, each with its own strengths and weaknesses, ready to be assembled into dynamic applications.
The Big Seven:
JavaScript offers seven fundamental data types:
- String: Holds text, enclosed in quotes. Imagine labels, descriptions, or user input. “Hello, world!” is a string.
- Number: Stores numeric values for calculations and measurements. Prices, ages, and coordinates are all numbers.
- Boolean: Represents true or false values, perfect for making decisions. Is the user logged in? True or false?
- Null: Represents the absence of a value, like an empty box waiting to be filled.
- Undefined: Indicates a variable that hasn’t been assigned a value yet, like a box without a label.
- BigInt: Introduced in ES6, it holds extremely large numbers beyond the normal number range, like astronomical distances.
- Symbol: Unique identifiers for objects, like secret keys for special features.
Choosing the Right Tool:
Knowing which type to use is crucial for efficient and clear code. Here’s a quick guide:
- Strings: Use for text, names, or any data that needs to be treated as text.
- Numbers: Perfect for calculations, measurements, and anything that involves arithmetic.
- Booleans: Make decisions based on true/false conditions.
- Null & Undefined: Handle missing or unassigned values.
- BigInt: Tackle massive numbers that regular numbers can’t handle.
- Symbol: Create unique identifiers for objects and prevent conflicts.
Beyond the Basics:
Data types are powerful, but they’re just the beginning. Learn about:
- Type conversions: Change data types when needed, like turning a string into a number.
- Arrays and objects: Complex data structures that hold collections of data types.
- Functions and operators: Tools to manipulate and work with your data.
Remember:
- Each data type has its own strengths and limitations.
- Choosing the right type makes your code clean and efficient.
- Practice using all the tools in your JavaScript toolbox to become a master coder!
Bonus Tip: Explore advanced data types like sets and maps for even more powerful data manipulation.
With a solid understanding of data types, you’ll be well on your way to building amazing things in JavaScript!
Imagine for a moment that you are faced
with the task of moving all your belongings to a new place. What steps would you take to
make the process more efficient? Well, you probably start by sorting
items and packing them into boxes and then labeling those boxes so that you
have an idea of what each one contains. After moving them, you put each box in the room it belongs
to make unpacking quicker and easier. You can also think of programming in
a similar way to packing and moving boxes. You have many different data
types at your disposal but coding efficiently starts with
knowing when and where to use them. In this video you learn to identify
the primitive data types in JavaScript. You will learn about their specific use
cases and when to use each data type. There are seven primitive
data types in JavaScript. These are string, number, Boolean,
null, undefined, BigInt and symbol. Let’s begin by learning about the first
two which are strings and numbers. Let’s say that you are building
an E-commerce app for selling guitars. When a user views the page for
the most popular model, you want them to see the name
of the guitar, the description, the best guitar around and
the price of 375. Seems simple enough, right? But how can you ensure that the
information displayed on screen is stored effectively so that the app can use it? You would do this by using the most
appropriate data types but what does data mean exactly? Well, each piece of information in
your app has a different value and all values are collectively referred
to as data but the values differ and therefore need to be stored differently. For example, you store the name and
description as text values and the price as a numerical value. In JavaScript, text values are known
as the string data type while numerical values are referred
to as the number data type. From a programming perspective,
making a distinction between numbers and text is important because they
adhere to different rules. For example, to build a number, you
simply type in the numerical values but to build a string in JavaScript, the characters must be enclosed in
either single or double quotes. There is also a difference in the number
of combinations that the number and string data types can store. The number data type has a very wide range
in JS enough for most common use cases. However, it is limited up to a point
determined by JavaScript calculation capabilities. The string data type practically has
an unlimited number of combinations of characters. There is almost an infinite number of
ways we can combine different characters into strings. Okay, so back to our app example, the data
must be stored using different types. The price will be stored as
a number while the name and description will be stored as strings
with each one wrapped in double quotes. You now know that the string data type is
great for storing values such as titles and descriptions while the number
data type is better suited for prices or any value that you
would like to calculate. However, there are additional data
types in JavaScript to help you tackle different tasks. Next let’s explore each of the remaining
data types and their specific use cases to better understand how you
might make good use of them. Let’s think of each one as a box. Like I mentioned earlier, the Boolean data
type has only two values, true and false. This means that it is useful for
making decisions. Sometimes it’s necessary to know when
a variable does not contain a value. And JavaScript has two data
types to express just that. First, there is the null data type
which only has the value null and represents the absence of value. You also have the undefined data type
which can only hold the value undefined and usually refers to a variable that
has not yet been assigned a value. The capabilities of JavaScript have
evolved over time and version ES6 introduced two new primitive data
types to help with more complex tasks. One is the BigInt data type which
is like an extra large box that can accommodate a much greater range of
numbers than the number data type. Finally, there is the symbol data type
which can be used as a unique identifier. Think of it as having multiple
boxes with the same label and using different serial numbers
to avoid mixing them up. In this video, you’ve learned about the various
data types available in JavaScript. Remember that every data type
has a specific use case and knowing when to apply each one will make
you a better coder, see you next time.
Video: Numbers
Key Points:
- JavaScript’s number data type stores both integers and decimals.
- Basic math operations like addition, subtraction, multiplication, and division are performed using familiar symbols.
- Exponents (double star) and modulo (remainder) operations are available for more complex calculations.
- Parentheses control the order of operations, following the standard math sequence by default.
Takeaways:
- Understanding the number data type and its operators is crucial for writing numeric calculations in JavaScript.
- Using parentheses effectively ensures accurate results by controlling the order of operations.
- Practice with different operators and expressions to solidify your understanding.
Bonus:
- Explore additional mathematical functions like square root, absolute value, and trigonometry in JavaScript.
- Experiment with combining operators and parentheses to create complex calculations.
Remember: Mastering the number data type and its operators opens doors to a world of numeric manipulation in your JavaScript code!
Welcome, aspiring coders! Today, we embark on a journey into the fascinating realm of numbers in JavaScript. These aren’t just digits on a screen; they’re the building blocks of countless calculations, animations, and dynamic features that make your JavaScript programs shine.
Meet the Number Data Type:
At the heart of it all lies the number data type. This versatile friend stores both whole numbers (like 10) and numbers with decimal points (like 3.14). It’s the backbone of calculations, measurements, and even powering dynamic web elements.
Performing Math Magic:
JavaScript equips you with a powerful toolbox of operators to perform various mathematical feats:
- Basic Arithmetic:
- + (Addition): Combine numbers like 5 + 3 to get 8.
- – (Subtraction): Subtract one number from another, like 10 – 5 to get 5.
- *** (Multiplication):** Multiply two numbers, like 4 * 2 to get 8.
- / (Division): Divide one number by another, like 12 / 3 to get 4.
- Advanced Operations:
- % (Modulo): Find the remainder after dividing one number by another, like 10 % 3 to get 1.
- **** (Exponentiation):** Raise a number to a power, like 2 ** 3 to get 8.
Precision Matters:
JavaScript numbers have limitations. While they can handle many calculations, they can’t represent infinitely precise values. Remember this when dealing with very large or very small numbers.
Beyond Basics:
Numbers go beyond simple calculations. They can:
- Control program flow: Use conditions based on numbers to make your program follow different paths.
- Animate elements: Change the position, size, or opacity of elements on the web using numbers.
- Represent data: Numbers can store measurements, prices, scores, and more, allowing you to analyze and visualize them.
Tips and Tricks:
- Use parentheses to control the order of operations, just like in math!
- Utilize built-in math functions like
Math.sqrt()
for square root orMath.random()
for generating random numbers. - Practice writing different expressions and calculations to solidify your understanding.
Remember:
- Numbers are the workhorses of JavaScript, powering countless features and functionalities.
- Mastering basic and advanced operations opens doors to building dynamic and interactive applications.
- Practice, explore, and have fun experimenting with the magic of numbers in your JavaScript code!
Bonus:
- Learn about different number formats like hexadecimal and binary.
- Explore advanced libraries like NumPy for scientific computing in JavaScript.
- Dive into data analysis with libraries like D3.js to visualize and manipulate numerical data.
The world of numbers in JavaScript awaits! So, grab your coding tools and start unleashing their power in your programs!
In JavaScript, like in other
programming languages, there are different data types. The number of data type is a foundational part
of JavaScript as a programming language
because it represents both integer and
decimal point numbers. Without it, you wouldn’t
be able to code and with such a crucial data type we better get
started right away. Let me demonstrate
the number data type. I type the value 123 into the console and
press ”Enter.” Notice that the output is 123. Next, on a new line, I type a decimal value, 123.456 which is also
a number data type. I press the Enter
key again and get the decimal value 123.456. In JavaScript, we can use numbers to perform
math operations. For example, I can code 2 plus 2 and get the value
of 4 returned. Just like in regular
mathematics, we use the plus
symbol for addition. Similarly, use the minus
symbol to perform subtraction. For example, 4 minus 2
returns the value of 2. For multiplication use
the asterisk or star key so 4 times 4,
will return 16. For division use the
forward-slash key 16 divided by 4 returns
the value of 4. You can use a double
star sign to perform exponential calculations for slightly more
complex arithmetic. For example, 10 to
the power of 2, 10 times 10 will return 100. A final example is the remainder
or the modulus operator. This checks how many times
you can fit one number into the other and then
return the remainder. If I type 9 modulus 8, the value of one is returned, or 16 modulus 8 returns a zero. This is because the number eight divides into the
number 16 evenly. There is no remainder as
represented here by the zero. Besides basic
mathematical operations, you can also use parentheses to group more complex calculations. For example, 2
times 4 plus 8 can return a different
answer depending on the order used
for calculation. For example, multiplying 2 times 4 and then adding
the value of 8 returns 16 but 2 times the value
of 4 plus 8 returns 24. By using parentheses, I can control the order
of calculations. Without parentheses,
JavaScript will follow the standard mathematical
sequence of calculation. In this case, the multiplication would take precedence
and be done first so the 2 times 4
happens first and then the 8 is added returning
a value of 16. Remember I can
override that using parentheses and get
a different result. That’s an example of
using parentheses and JavaScript with numbers and
mathematical operators. Some of the most
common JavaScript mathematical operators are plus, minus, times,
division, and modulus. If you’d like to learn more
about mathematical operators, there’s an additional reading
at the end of this lesson.
Video: Strings
Key Points:
- Strings represent sequences of characters enclosed in single or double quotes.
- Strings are one of the most common data types in JavaScript.
- They can contain letters, numbers, symbols, and most other characters.
- Delimiters (quotes) define the boundaries of a string.
- Avoid nesting single quotes within single quotes, use double quotes instead.
- Strings cannot break onto new lines without special characters.
Takeaways:
- Understanding strings is essential for basic JavaScript programming.
- Practice creating and manipulating strings to solidify your understanding.
- Consistency in using single or double quotes is recommended for clarity.
Bonus:
- Explore string methods for searching, modifying, and manipulating text.
- Learn about string interpolation for embedding variables within strings.
- Discover advanced techniques like regular expressions for complex text processing.
Remember, strings are the building blocks of text in JavaScript. Master them, and you’ll be well on your way to coding amazing things!
Welcome, aspiring coders, to the world of JavaScript strings! These are your building blocks for text, messages, and dynamic content in your programs. Let’s dive into their magic and unlock their potential!
What are Strings?
Imagine a string of pearls, each one a character, strung together to form something beautiful. In JavaScript, strings are like those pearls, but they hold letters, numbers, symbols, and even emojis! Single or double quotes enclose them, making them a discrete unit of text.
Creating Strings:
It’s easy to bring your strings to life! Simply enclose your desired characters within quotes. For example:
'Hello, world!'
– A friendly greeting."My favorite number is 13."
– Sharing a quirky fact.''
– Celebrating in style with emojis.
String Superpowers:
Strings are more than just text; they have superpowers! You can:
- Concatenate: Join multiple strings like pearls, using the “+” operator:
'Hello' + ' ' + 'world!'
becomes “Hello, world!”. - Access characters: Peek inside your string, each character like a pearl at an index:
'JavaScript'[0]
reveals “J”. - Change case: Make your strings uppercase or lowercase for different moods:
'hello'.toUpperCase()
becomes “HELLO”. - Search and replace: Find and swap characters like rearranging pearls:
'I love coding'.replace('love', 'like')
becomes “I like coding”.
Beyond the Basics:
Strings are versatile! Use them to:
- Build user interfaces: Display text, labels, and dynamic content on your web pages.
- Store data: Use strings to represent names, descriptions, or any text-based information.
- Perform complex operations: Combine string methods like splitting, trimming, and formatting for advanced text manipulation.
Tips and Tricks:
- Escape special characters like quotes within your strings using backslashes.
- Use string templates for cleaner and more readable code.
- Practice with different string methods to explore their full potential.
Remember:
Strings are the voice of your JavaScript programs. Mastering them opens doors to creating interactive and engaging experiences. So, grab your quotes and start crafting your string masterpieces!
Bonus:
- Explore advanced string methods like regular expressions for powerful text processing.
- Learn about string encoding and decoding for internationalization.
- Discover libraries like Moment.js for working with dates and times as strings.
The world of strings awaits! With practice and creativity, you’ll be weaving your own JavaScript magic in no time.
Since you’re new to JavaScript, you might not be
familiar with strings. Strings are used to
represent and work with a sequence of characters while
programming in JavaScript. Let me explain how they work. To demonstrate the
concept of strings, I have the developer tools
open in my browser and the Console tab is
selected. What is a string? A string in JavaScript
is a collection of characters enclosed by single
quotes, double quotes. Such a collection of characters is known as a string datatype. Strings are one of
the most common types of data you’ll be working with. To code a string, I type in a pair of single
quotation marks. This piece of code with
just an opening and closing single quote is referred
to as an empty string. To build an empty string, I can also use double
quotation marks. While empty strings have
their place in JavaScript, they’re not very versatile. But strings don’t
have to be empty, so let me build a
non-empty string with some letters and
an exclamation mark. I do this by typing
the words hello there, and an exclamation mark within a pair of single
quotation marks. Besides letters and
punctuation symbols, we can add almost
any other character into a string,
including numbers. For example, I can
type ‘hello there! ‘ and follow it up with
several symbols and numbers. This is still a valid string. There’s one thing
that strings can’t do and that is break
onto the next line. When I type a single quotation
mark, the word hello, and then press Enter before typing the second
quotation mark, it results in an error which
stops the code from running. The same happens if I use
double quotation marks. When you use single
or double quotes to surround string values, these characters are
referred to as delimiters. This is because I
use them to delimit a given string value from
the rest of my code. There are some unusual
situations that can trip you up when you first start
using strings in JavaScript. For example, let’s say that I want to
create a new string. I do this by typing a
single quotation mark, followed by the phrase, it is a lovely day, and I close the string with a second single quotation mark. Now I want to use the
contraction of it is by using an apostrophe
but again, error code. This is because JavaScript
reads the word it, that is the first two
letters as forming a string, and then it doesn’t
understand the rest of the code because
of the apostrophe. To fix this issue, I need to nest single quotes
inside double quotes. I do this by replacing the original single
quotation marks on either side of the phrase
with double quotation marks, and now you’ll notice
there are no more errors. You can make single
and double quotes too but it’s better to
stick with one or the other because it can
be confusing and lacks consistency, and
there you have it. You have learned what
a string datatype is and what an empty string is. You can also explain what the string datatype
is in JavaScript, I encourage you to try and make some more strings while
practicing coding.
Video: Booleans
Key Points:
- Booleans represent true or false values, used for decision making in code.
- Comparison operators like
==
and!=
check if two values are equal or not. - Strict equality (
===
and!==
) considers both value and type for comparison. - Inequality operators (
!=
and!==
) check if values are not equal. - Understanding Boolean logic is crucial for controlling program flow.
Takeaways:
- Mastering comparison operators and Booleans empowers you to make decisions in your Javascript code.
- Practice with different operators and data types to solidify your understanding.
- Remember, strict comparisons can be more reliable but less forgiving than loose comparisons.
Bonus:
- Explore other comparison operators like
<
and>
for more complex checks. - Learn about logical operators like
&&
and||
for combining comparisons. - Discover conditional statements like
if
andelse
to control program flow based on Boolean values.
Remember: The Boolean data type is a powerful tool for building dynamic and interactive Javascript programs. Master it, and you’ll be well on your way to coding success!
Welcome, aspiring coders, to the world of Booleans! These tiny giants might seem simple, holding only “true” and “false” values, but they’re the foundation of logic in Javascript. Mastering them is like unlocking the secret code to making your programs think, react, and make choices.
What are Booleans?
Think of Booleans as tiny switches, each labeled “true” or “false.” They control the flow of your program, deciding which paths to take and what to do next. Imagine a light switch; one click is “true,” the light is on, the other click is “false,” the darkness reigns.
Comparing Values:
Booleans shine when comparing values. You can use operators like ==
(equal to), !=
(not equal to), <
(less than), and >
(greater than) to set your Boolean switches. For example:
5 == 3
is false, because 5 is not equal to 3.10 > 2
is true, because 10 is indeed greater than 2.
Strict Equality:
But there’s a twist! Javascript can be picky about types. Sometimes, comparing values with just ==
might not be enough. Use ===
for strict equality, ensuring both value and type match. For example:
10 == "10"
is true, because they have the same value.10 === "10"
is false, because they have the same value but different types (number and string).
Beyond Comparisons:
Booleans aren’t limited to comparing numbers. They can also be used with:
- Logical operators: Combine Booleans like
&&
(and),||
(or), and!
(not) to create complex logic. For example:(age > 18) && (isCitizen)
checks if someone is both over 18 and a citizen to vote. - Conditional statements: Use
if
andelse
statements to control program flow based on Boolean values. For example:if (score > 70) { console.log("Passed!"); } else { console.log("Try again!"); }
Tips and Tricks:
- Remember,
true
is always a truthy value, even non-zero numbers or strings like “hello.” false
is a falsy value, along with 0, null, and undefined.- Use Boolean functions like
isNaN()
to check if a value is not a number.
Remember:
Booleans are the gatekeepers of logic in Javascript. Mastering them unlocks the power to make your programs think, react, and make decisions. So, flip those switches, explore the possibilities, and watch your code come alive!
Bonus:
- Learn about bitwise operators for advanced data manipulation.
- Discover libraries like Lodash for efficient Boolean operations.
- Explore advanced concepts like truthiness and falsiness for even deeper understanding.
The world of Booleans awaits! Embrace their power, and watch your Javascript programs reach new heights of logic and control.
The Boolean data type is used to check if a statement
is true or false, which makes it a
foundational part of knowing how to
use JavaScript. It has many uses,
but in this video, I will focus on how
to get the result of a comparison to determine if two values are
the same or not. What does a Boolean datatype? To understand the answer
to this question, let’s think about a
real life scenario of comparing numbers, such as, for example, checking if number 1 is
smaller than number 2. In JavaScript, I
do it like this, 1 less than sign 2. When I press the Enter key, JavaScript says that
this is a true claim. Let’s do some other comparisons. Let’s check if one
is greater than two, 1 greater than sign 2. This code returns a value of false of the Boolean data type. No matter how I compare numbers, the result of the
comparison will always be either true or false. There are no maybe’s here. That’s why the
Boolean data type has only two possible
values, true and false. Besides the less than and
the greater than operator, I can also use some other
operators to compare numbers. It might help to think of these various comparison
operators, those tests. Let’s say I wanted to
test if the comparison of two numbers is
correct or incorrect. Now I will run a few tests with some additional operators, starting with checking
for equality, 1 equals equals 2. I’m claiming that 1 is equal to 2 and JavaScript returns false. No, 1 is not equal to 2. My claim is false. When first introduced to the syntax with two
consecutive equal signs, it is not uncommon for people
to be slightly confused. Why the double equals sign? After all, you know
that in mathematics you only need a single equal
sign to signal equality. But in JavaScript, I use a single equal sign as the
assignment operator to assign a value from the right side
of the assignment operator to the variable on the left side of the
assignment operator. For example, I can type
var score equals 100 to declare a variable
called score and assign it to the value 100. In other words, I can now
confirm that the value of score is 100 by typing
out score in the console. Indeed 100 it is. In contrast, in JavaScript
the equality operator has to equal signs and it
checks only for value. Additionally, there’s also the strict equality
operator that has three equal signs
and it checks for both the value and type. For example, if I use
the equality operator, let me type 100
double equal sign, double quotation, number 100, and close double quotation, the console will return
the Boolean value of true. By using the double equals sign, I compare only this
value and not the type. JavaScript checks
only if 100 is equal to 100 regardless
of the datatype. It ignores the fact that
the 100 on the left of the equality operator without the double-quotes is a number, and that the 100 on the right of the equality operator with the
double quotes is a string. The strict equality operator
is more unforgiving. It checks for both
the quality of value and the quality of type. Therefore, comparing
the number of 100 without quotes with a string 100 with double-quotes
will return a Boolean value of false. Why is this false? It is false because although the value is the same,
the type is not. The number 100 does not have the same type as the string 100. There’s also an operator
that’s the opposite of the equality operator,
the inequality operator. It’s a combination of
an exclamation mark and an equal sign.
Let’s test it. I take number 1, exclamation mark the equals
sign and number 1 again. It returns a Boolean
value of false because it is false to say that
one is not equal to one. Additionally, just like there’s the strict equality operator, there’s also its opposite in the form of the strict
inequality operator. This operator is an
exclamation mark with two equal signs. Let’s type number 1 as a number, exclamation mark the
equals sign twice, and then number 1 inside double quotes that
is as a string. This returns a Boolean value of true because the
number one is not the same as a string 1 by
both the value and the type. It’s true that these two
values are not the same. There are other
operators in JavaScript, and there are some
additional concepts like operator precedence and
operator associativity, but we’ll skip this for now. With the examples
covered in this video, you should have a
basic grasp of how the Boolean data type works
and what it’s useful for. You will encounter
Boolean values again because there are
other important ways in which you can use them in your code besides comparing
numbers and strings.
Reading: Operators in depth
Reading
In this reading, you will learn about additional operators, operator precedence and operator associativity. I’ll also provide you with some examples of logical operators.
1. Additional operators
- Logical AND operator: &&
- Logical OR operator: ||
- Logical NOT operator: !
- The modulus operator: %
- The equality operator: ==
- The strict equality operator: ===
- The inequality operator: !=
- The strict inequality operator: !==
- The addition assignment operator: +=
- The concatenation assignment operator: += (it’s the same as the previous one – more on that later)
The logical AND operator in JavaScript: &&
The logical AND operator is, for example, used to confirm if multiple comparisons will return true.
In JavaScript, this operator consists of two ampersand symbols together: &&.
Let’s say you’re tasked with coming up with some code that will check if the currentTime variable is between 9 a.m. and 5 p.m. The code needs to console.log true if currentTime > 9 and if currentTime < 17.
Here’s a solution:
var currentTime = 10;
console.log(currentTime > 9 && currentTime < 17);
How does this code work?
First, on line one, I set the currentTime variable, and assign the value of 10 to it.
Next, on line two I console log two comparisons:
currentTime > 9
currentTime < 17
I also use the && logical operator to join the two comparisons.
Effectively, my code is interpretted as the following:
console.log(10 > 9 && 10 < 17);
The comparison of 10 > 9 will return true.
Also, the comparison of 10 < 17 will return true.
This means I can further re-write the line two of my solution as follows:
console.log(true && true);
In essence, this is how my code works.
Now, the question is, what will be the result of console.log(true && true)?
To understand the answer, you need to know the behavior of the && logical operator.
The && logical operator returns a single value: the boolean true or false, based on the following rules:
- It returns true if both the values on its right and on its left are evaluated to true
- It returns false in all the other instances
In other words:
console.log(true && true) will output: true
console.log(true && false) will output: false
console.log(false && true) will output: false
console.log(false && false) will output: false
The logical OR operator in JavaScript: ||
The logical OR operator in JavaScript consists of two pipe symbols together: ||.
It is used when you want to check if at least one of the given comparisons evaluates to true.
Consider the following task: You need to write a program in JavaScript which will return true if the value of the currentTime variable is not between 9 and 17. Put differently, your code needs to console.log true if the value of the variable currentTime is either less than 9 or greater than 17.
Here’s a solution:
var currentTime = 7;
console.log(currentTime < 9 || currentTime > 17);
In line one of the code I assign the number 7 to the variable currentTime.
On line two, I console log the result of checking if either currentTime < 9 or currentTime > 17 will evaluate to true.
It’s the same as this:
var currentTime = 7;
console.log(true || false);
Here are the rules of how the || operator evaluates given values:
console.log(true || true) will output: true
console.log(true || false) will output: true
console.log(false || true) will output: true
console.log(false || false) will output: false
The logical OR operator will always return true, except when both sides evaluate to false. In other words, for the logical OR operator to return false, the results of both comparisons must return false.
Going back to the example of checking if either currentTime < 9 or currentTime > 17, this makes sense: the only time you will get false is when the value stored in the currentTime variable is greater than 9 and less then 17.
The logical NOT operator: !
In JavaScript, the logical NOT operator’s symbol is the exclamation mark: !.
You can think of the ! operator as a switch, which flips the evaluated boolean value from true to false and from false to true.
For example if I assign the boolean value of true to the petHungry variable:
var petHungry = true;
…then I can console log the fact that the pet is no longer hungry by using the ! operator to flip the boolean value stored inside of the petHungry variable, like so:
console.log(‘Feeding the pet’); console.log(“Pet is hungry: “, !petHungry); console.log(petHungry);
This is the output of the above code:
Pet is hungry: true
Feeding the pet
Pet is hungry: false
true
The reason for the changed output in the console is because you have flipped the value stored inside the petHungry variable, from true to false.
Notice, however, that the code on line five of the example above still outputs true – that’s due to the fact that I didn’t reassign the value of the petHungry variable.
Here’s how I could permanently change the value stored in the petHungry variable from true to false:
var petHungry = true;
petHungry = !petHungry;
In this example, I first assign the value of true to the new variable of petHungry. Then, on line two, I assign the opposite value, the !true – read: not true – to the existing petHungry variable.
The modulus operator: %
The modulus operator is another mathematical operator in JavaScript. It returns the remainder of division.
To demonstrate how it works, imagine that a small restaurant that has 4 chairs per table, and a total of 5 tables, suddenly receives 22 guests.
How many guests will not be able to sit down in the restaurant?
You can use the modulus operator to solve this.
console.log(22 % 5); // 2
The output is 2, meaning, when I divide 22 and 5, I get a 4, and the remainder is 2, meaning, there are 2 people who couldn’t get a place in this restaurant.
The equality operator, ==
The equality operator checks if two values are equal.
For example, this comparison returns true: 5 == 5. Indeed, it is true that 5 is equal to 5.
Here’s an example of the equality operator returning false: 5 == 6. Indeed, it is true that 5 is not equal to 6.
Additionally, even if one of the compared values is of the number type, and the other is of the string type, the returned value is still true: 5 == “5”.
This means that the equality operator compares only the values, but not the types.
The strict equality operator, ===
The strict equality operator compares for both the values and the data types.
With the strict equality operator, comparing 5 === 5 still returns true. The values on each side of the strict equality operator have the same value and the same type. However, comparing 5 == “5” now returns false, because the values are equal, but the data type is different.
The inequality operator, !=
The inequality operator checks if two values are not the same, but it does not check against the difference in types.
For example, 5 != “5” returns false, because it’s false to claim that the number 5 is not equal to number 5, even though this other number is of the string data type.
The strict inequality operator !==
For the strict inequality operator to return false, the compared values have to have the same value and the same data type.
For example, 5 !== 5 returns false because it is false to say that the number 5 is not of the same value and data type and another number 5.
However, comparing the number 5 and the string 5, using the strict inequality operator, returns true.
console.log(5 !== "5")
2. Using the + operators on strings and numbers
Combining two strings using the + operator
The + operator, when used with number data type, adds those values together.
However, the + operator is also used to join string data type together.
For example:
"inter" + "net" // "internet"
"note" + "book" // "notebook"
If the + operator is used to join strings, then it is referred to as the concatenation operator, and you’ll say that it’s used to concatenate strings.
When used with numbers, the + operator is the addition operator, and when used with strings, the + operator is the concatenation operator.
Combining strings and numbers using the + operator
But what happens when one combines a string and a number using the + operator?
Here’s an example:
365 + " days" // "365 days"
12 + " months" // "12 months"
Here, JavaScript tries to help by converting the numbers to strings, and then concatenating the number and the string together, ending up with a string value.
The process of this “under-the-hood” conversion of values in JavaScript is referred to as “coercion”. JavaScript coerces a number value to a string value – so that it can run the + operator on disparate data types.
The process of coercion can sometimes be a bit unexpected.
Consider the following example:
1 + "2"
What will be the result of 1 + “2”?
Note that the value of 1 is of the number data type, and the value of “2” is of the string data type, and so JavaScript will coerce the number 1 to a string of “1”, and then concatenate it with the string of “2”, so the result is a string of “12”.
The addition assignment operator, +=
The addition assignment operator is used when one wants to accumulate the values stored in a variable.
Here’s an example: You are counting the number of overtime hours worked in a week.
You don’t have to specify the type of work, you just want to count total hours.
You might code a program to track it, like this:
var mon = 1;
var tue = 2;
var wed = 1;
var thu = 2;
var fri = 3;
console.log(mon + tue + wed + thu + fri); // 9
You can simplify the above code by using the addition assignment operator, as follows:
var overtime = 1;
overtime += 2;
overtime += 1;
overtime += 2;
overtime += 3;
console.log(overtime); // 9
Using the addition assignment operator reduces the lines of your code.
The concatenation assignment operator, +=
This operator’s syntax is exactly the same as the addition assignment operator. The difference is in the data type used:
var longString = "";
longString += "Once";
longString += " upon";
longString += " a";
longString += " time";
longString += "...";
console.log(longString); // "Once upon a time..."
Operator precedence and associativity
Operator precedence is a set of rules that determines which operator should be evaluated first.
Consider the following example:
1 * 2 + 3
The result of the above code is 5, because the multiplication operator has precedence over the addition operator.
Operator associativity determines how the precedence works when the code uses operators with the same precedence.
There are two kinds:
- left-to-right associativity
- right-to-left associativity
For example, the assignment operator is right-to-left associative, while the greater than operator is left-to-right associative:
var num = 10; // the value on the right is assigned to the variable name on the left
5 > 4 > 3; // the 5 > 4 is evaluated first (to `true`), then true > 3 is evaluated to `false`, because the `true` value is coerced to `1`
Reading: Exercise: Advanced use of operators
Reading
Task 1: Using the logical && operator
You are coding an RPG game, where each character has certain skill levels based on the value saved in their score.
- Create a variable named score and set it to 8
- Use console.log() that includes the string “Mid-level skills:” and compares the score variable to above 0 and below 10 using the && operator
The expected output in the console should be: “Mid-level skills: true”.
var score = 8
console.log("Mid-leve skills:", score > 0 && score < 10 )
Mid-leve skills: true
Task 2: Using the logical || operator
Imagine you are coding a video game. Currently, you’re about to code some snippets related to the game over condition.
You need to code a new variable named timeRemaining and set it to 0. You also need to code a new variable named energy and set it to 10.
Next, you should write a piece of code that could be used to determine if the game is over, based on whether either the value of the timeRemaining variable is 0 or the value of the energy variable is 0.
Complete the task using the following steps:
- Declare the variable timeRemaining, and assign the value of 0 to it.
- Declare the variable energy, and assign the value of 10 to it.
- Console log the following parameters: “Game over: “, and timeRemaining == 0 || energy == 0
Note that the expected output in the console should be: “Game over: true”.
var timeRemaining = 0
var energy = 10
console.log("Game over:", timeRemaining == 0 || energy == 0)
Game over: true
Try changing the timeRemaining variable to anything above 0 and then see how it affects the result.
Task 3: Using the modulus operator, %, to test if a given number is odd
You need to code a small program that takes a number and determines if it’s an even number (like 2, 4, 6, 8, 10).
To achieve this task, you need to declare six variables, as follows:
- The first variable, named num1, should be assigned a number value of 2.
- The second variable, named num2, should be assigned a number value of 5.
- The third variable, named test1, should be assigned the calculation of num1 % 2. Note: executing this code will return a number.
- The fourth variable, named test2, should be assigned the calculation of num2 % 2. Note: executing this code will also return a number.
- The fifth variable, named result1, should be assigned the result of comparing if the number stored in the test1 variable is not equal to 0, in other words, this: test1 == 0.
- The sixth variable, named result2, should be assigned the result of comparing if the number stored in the test2 variable is not equal to 0, in other words, test2 == 0.
Run console log two times after you’ve set the variables:
- The first console log should have the following code between parentheses: “Is”, num1, “an even number?”, result1
- The second console log should have the following code between parentheses: “Is”, num2, “an even number?”, result2
Note: The output to the console should be as follows:
Is 2 an even number? true
Is 5 an even number? false
var num1 = 2
var num2 = 5
var test1 = num1 % 2
var test2 = num2 % 2
var result1 = test1 == 0
var result2 = test2 == 0
console.log("Is", num1, "an even number?", result1)
console.log("Is", num2, "an even number?", result2)
Is 2 an even number? true
Is 5 an even number? false
Try it yourself with different values to explore the modulus operator.
Task 4: Add numbers using the + operator
Console log the result of adding two numbers, 5 and 10, using the + operator.
Note: This task should be completed on a single line of code. The output in the console should be 15.
console.log(5 + 10)
15
Task 5: Concatenate numbers and strings using the + operator
Code three variables:
- The first variable should be a string with the following value: “Now in “. Name the variable now.
- The second variable should be a number with the value: 3. Name the variable three.
- The third variable should a string with the following value: “D!”. Name the variable d.
- Console log the following code: now + three + d.
Note: The expected output should be: “Now in 3D!”.
var now = "Now in "
var three = 3
var d = "D!"
console.log(now + three + d)
Now in 3D!
Task 6: Use the += operator to accumulate values in a variable
Code a new variable and name it counter, assigning it to the value of 0.
On the next line, use the += operator to increase the value of counter by 5.
On the next line, use the += operator to increase the value of counter by 3.
On the fourth line, console log the value of the counter variable.
Note: The output value should be 8.
var counter = 0
counter += 5
counter += 3
console.log(counter)
8
Reading: Advanced use of operators (solutions)
Reading
Task 1 Solution
var score = 8;
console.log("Mid-level skills:", score > 0 && score < 10)
Mid-level skills: true
Task 2 Solution
var timeRemaining = 0;
var energy = 10;
console.log("Game over:", timeRemaining == 0 || energy == 0);
Game over: true
Task 3 Solution
var num1 = 2;
var num2 = 5;
var test1 = num1 % 2;
var test2 = num2 % 2;
var result1 = test1 == 0;
var result2 = test2 == 0;
console.log("Is", num1, "an even number?", result1);
console.log("Is", num2, "an even number?", result2);
Is 2 an even number? true
Is 5 an even number? false
Task 4 Solution
console.log(5 + 10); // 15
15
Task 5 Solution
var now = "Now in ";
var three = 3;
var d = "D!"
console.log(now + three + d); // "Now in 3D!"
Now in 3D!
Task 6 Solution
var counter = 0;
counter += 5;
counter += 3;
console.log(counter); // 8
8
Practice Quiz: Knowledge check: Welcome to Programming
What is the data type of the value “Hello, World”?
string
That’s correct! The value of “Hello, World” is of the string data type.
What is the data type of the value true ?
boolean
That’s correct! The values of true and `false are of the boolean data type.
What is the % operator?
The modulus operator
That’s correct! The modulus operator is represented using the % symbol.
What happens when you use the + operator on two strings?
They get joined into a single string
That’s correct! Using the + operator on two strings joins the strings together.
What is the operator symbol && represent in JavaScript?
The logical AND operator
That’s correct! In JavaScript, the && is the logical AND operator.
What happens when you use the + operator on a string and a number?
They get joined together as if both of them were strings
That’s correct! Using the + operator on a string and a number joins them together as if both of them were strings.
What is the value of i after the following code runs?
var i = 7;
i += 1;
i += 2;
10
That’s correct. 1 is added to i and the result is stored in i . The value is now 8. Then, 2 is added to i and the result is stored in i . The value is now 10 .
Reading: JavaScript improvements
Reading
In this reading, you will learn about the history of JavaScript and the importance of ECMA (European Computer Manufacturers Association) and ECMAScript.
JavaScript is a programming language that had humble beginnings.
It was built in only 10 days in 1995 by a single person, Brendan Eich, who was tasked with building a simple scripting language to be used in version 2 of the Netscape browser. It was initially called LiveScript, but since the Java language was so popular at the time, the name was changed to JavaScript – although Java and JavaScript are in no way related.
For the first few years, after it was built, JavaScript was a simple scripting language to add mouseover effects and other interactivity. Those effects were being added to webpages using the <script> HTML element.
Inside each of the script elements, there could be some JavaScript code. Due to the rule that HTML, CSS, and JavaScript must be backward compatible, even the most advanced code written in JavaScript today ends up being written between those script tags.
Over the years, JavaScript grew ever more powerful, and in recent times, it’s continually touted as among the top three commonly used languages.
In 1996 Netscape made a deal with the organization known as ECMA (European Computer Manufacturers Association) to draft the specification of the JavaScript language, and in 1997 the first edition of the ECMAScript specification was published.
ECMA publishes this specification as the ECMA-262 standard.
You can think of a standard as an agreed-upon way of how things should work. Thus, ECMA-262 is a standard that specifies how the JavaScript language should work.
There have been 12 ECMA-262 updates – the first one was in 1997.
JavaScript as a language is not a completely separate, stand-alone entity. It only exists as an implementation. This implementation is known as a JavaScript engine.
Traditionally, the only environment in which it was possible to run a JavaScript engine, was the browser. More specifically, a JavaScript engine was just another building block of the browser. It was there to help a browser accomplish its users’ goal of utilizing the internet for work, research, and play.
So, when developers write JavaScript code, they are using it to interact with a JavaScript engine. Put differently, developers write JavaScript code so that they can “talk to” a JavaScript engine.
Additionally, the JavaScript engine itself comes with different ways to interact with various other parts of the browser. These are known as Browser APIs.
Thus, the code that you write in the JavaScript programming language allows you to: 1. Interact with the JavaScript engine inside of the browser 2. Interact with other browser functionality that exists outside of the JavaScript engine, but is still inside the browser.
Although traditionally it was possible to interact with the JavaScript engine only inside of the browser, this all changed in 2009, when Node.js was built by Ryan Dahl.
He came up with a way to use a JavaScript engine as a stand-alone entity. Suddenly, it was possible to use JavaScript outside of the browser, as a separate program on the command line, or as a server-side environment.
Today, JavaScript is ubiquitous and is running in browsers, on servers, actually, on any device that can run a JavaScript engine.
Reading: Additional resources
Reading
Here is a list of resources that may be helpful as you continue your learning journey.
These resources provide some more in-depth information on the topics covered in this module.
Mozilla Developer Network Expressions and Operators
Mozilla Developer Network Operator Precedence and Associativity
StackOverflow Developer Survey 2021 Most Popular Technologies
Conditionals and Loops
Video: Writing statements
This video introduces the fundamentals of conditional statements in JavaScript, focusing on if
and else
statements.
Key Takeaways:
- Decisions Everywhere: We constantly make decisions based on
true
orfalse
conditions, like choosing an umbrella if it’s raining. - Conditional Statements in JavaScript: Similar to real-life decisions, JavaScript
conditionals
execute code based ontrue
orfalse
conditions. - The
if
Statement: This basic conditional checks a condition and runs its code block only if the condition istrue
. - Comparison Operators: These operators like
==
,>
,<
, and!=
help evaluate conditions. - The
if-else
Statement: Handles bothtrue
andfalse
scenarios. Code for thetrue
case runs if the condition istrue
, otherwise theelse
block runs. - Beyond
if-else
: For more complex situations,else-if
statements allow testing multiple conditions sequentially.
Overall:
Mastering if
and else
statements is crucial for making decisions in your JavaScript programs. These powerful tools provide flexibility and control in your code’s execution.
Additional Notes:
- The summary condenses the main points while omitting redundant details and maintaining a professional tone.
- I replaced informal phrases like “you and I” with a more academic tone.
- The emphasis is on the functionality and purpose of conditionals rather than providing specific examples.
Welcome to the world of JavaScript! In this tutorial, we’ll dive into the fundamental building blocks of your programs: statements. These are the lines of code that tell the computer what to do, like printing messages, performing calculations, or making decisions.
1. Getting Started:
- Open your code editor or online coding platform.
- We’ll use simple examples to understand core concepts.
2. Basic Statements:
- Semicolons (;): These punctuate the end of most statements. You’ll see them after every line of code.
- Comments: Comments explain your code and don’t execute. Start them with // for single-line or /* */ for multi-line comments.
- Variable Declaration: Use
let
orconst
keywords to create variables that store data like numbers or text. Example:let name = "John";
- Assignment: Use
=
to assign values to variables. Example:age = 30;
3. Printing Output:
- Use the
console.log()
function to display messages in the browser console. Example:console.log("Hello, world!");
- You can print variables and expressions along with text. Example:
console.log("My name is", name);
4. Performing Calculations:
- JavaScript supports basic arithmetic operations like addition (+), subtraction (-), multiplication (*), and division (/).
- Combine numbers and variables in expressions. Example:
let total = price * quantity;
5. Making Decisions:
- Use conditional statements like
if
andelse
to control program flow based on conditions. if
checks a condition, and its code block runs only if the condition is true. Example:if (age >= 18) { console.log("You are eligible to vote."); }
else
provides an alternative code block to run if the condition is false. Example:else { console.log("You are under the voting age."); }
6. Putting it all Together:
- Combine these concepts to write meaningful programs.
- Example:
JavaScript
let message = "Welcome to the quiz!";
console.log(message);
let score = 0;
let answer = prompt("What is the capital of France?");
if (answer.toLowerCase() === "paris") {
score++;
console.log("Correct! Your score is now", score);
} else {
console.log("Sorry, the answer is Paris. Your score remains", score);
}
7. Practice and Explore:
- Keep practicing with different examples and experiment with different types of statements.
- Use online resources and tutorials to learn more advanced concepts like loops, functions, and objects.
Remember, writing statements is the foundation of your JavaScript journey. Master these basics, and you’ll be well on your way to building exciting and interactive programs!
Bonus Tips:
- Use whitespace and indentation to improve your code readability.
- Avoid errors by carefully checking your syntax and punctuation.
- Be consistent with your variable naming conventions.
- Most importantly, have fun and enjoy the process of learning JavaScript!
Every day from the
moment we wake up, you and I make decisions. From what clothes to wear, whether to have
tea or coffee for breakfast or even
what movie to watch. While some decisions
are complex, some can be relatively simple. We make them based on whether some condition is
either true or false. For example, if it’s
raining outside, we will likely
bring an umbrella. The condition here
is the weather. If it’s raining, we
take an umbrella. If it’s not, we don’t. In this video, you will learn about conditional
statements in JavaScript using the if
and else statements. In JavaScript, there are pieces of code
called conditionals, and developers can
use them to run code conditionally based on whether something is either
true or false. There are many types of
conditional statements, but the first one I
want you to learn about is something called
the if statement. The if statement checks
a condition and will execute a code block if the
condition is met or true. The condition criteria
are essential here. The block of code will
only get executed if the condition is evaluated to
the Boolean value of true. You can use many types of comparison operators to
evaluate the condition. These include operators
such as equal to, greater than, less than, and not equal to. You can find a complete list of comparison operators from
the additional reading at the end of this lesson. So far, you’ve learned about
using conditionals with binary conditions where a thing can be either true or false. However, in the world
of programming, things are often
not that simple. Imagine you are a
developer working on a website where a person can practice for their driving test. Part of the driving test
is that they must pass a theory exam of 50 questions based on the rules of the road. The exam has only two
results, pass or fail. If the student’s score is
greater than 40, they pass. If not, they fail. You need to output the exam
result to the learner. This is where another conditional
statement can be used, and it’s called the
if-else statement. This statement handles
both outcomes of our conditional request
using the else keyword. If a condition is
true, do something. If it’s false, do
something else. Recall, a driving test example. We can store the test
result in a variable. Suppose the variable
value is greater than 40. In that case, the true
block is executed, and you output a message to the console telling the
learner that they passed. Suppose the variable
value is less than 40. In that case, the false
block is executed, and you output a message to the console telling the learner
that they did not pass. There will be many occasions
where you will need to program for more complicated
conditions or scenarios. For example, you may want to
test multiple conditions. To do that, you can add an additional block called
the else-if statement. In this video, you learned about the conditional
statements, if and else. Conditional statements
are a powerful tool, and one of the
fundamentals you need to master when programming
in JavaScript.
Video: Working with conditional statements
This video explored:
- Conditional Statements: Using “if” and “else” to run code based on true/false conditions.
- if/else Example: Checking if a variable “result” is greater than 40, with “pass” or “fail” messages respectively.
- Multiple Conditions: Handling more than two options with nested “else if” statements.
- else if Example: Assigning medals based on the string value of variable “place” (“first”, “second”, “third”).
- Switch Statement: An alternative for handling multiple conditions more concisely.
- Switch Example: Using “switch” on “place” variable, with specific cases for each medal and a default case for other values.
Key Takeaways:
- “if/else” is useful for binary conditions (true/false).
- “else if” adds additional checks for complex scenarios.
- “switch” offers a cleaner approach for numerous conditions.
Comparison:
Feature | if/else | switch |
---|---|---|
Best for | Binary conditions | Multiple conditions |
Code Structure | Nested statements | Single block with cases |
Flexibility | Less flexible | More flexible for numerous conditions |
Remember: Both “if/else” and “switch” allow controlling program flow based on conditions. Choose the best approach based on the number and complexity of your conditions.
Additional Notes:
- The summary condenses the main points while omitting redundant details and maintaining a professional tone.
- I replaced informal contractions and phrases with clearer vocabulary.
- Technical terms like “syntax” and “operators” are retained for educational value.
Welcome to the world of control flow in JavaScript! In this tutorial, we’ll dive into the powerful tool of conditional statements, allowing your programs to make decisions and react based on different conditions.
1. Building Blocks:
- The
if
Statement: The backbone of conditional logic, checking a condition and executing its code block only if it’strue
. Example:
JavaScript
if (age >= 18) {
console.log("You can vote!");
}
- The
else
Statement: Provides an alternative code block if theif
condition isfalse
. - Comparison Operators: Tools like
==
,>
,<
, and!=
help evaluate conditions.
2. Beyond Binary Choices:
else if
Statements: Chain multipleif
checks for more complex scenarios. Example:
JavaScript
if (grade === "A") {
console.log("Excellent work!");
} else if (grade === "B") {
console.log("Great job!");
} else {
console.log("Keep practicing!");
}
- The
switch
Statement: Offers a cleaner approach for handling many conditions with distinct cases. Example:
JavaScript
switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("TGIF!");
break;
default:
console.log("Another day, another adventure!");
}
3. Putting it all Together:
- Combine different statements to build complex logic.
- Practice writing code for various scenarios.
- Remember proper indentation and clear variable names for readability.
4. Bonus Tips:
- Use logical operators like
&&
(and) and||
(or) to combine conditions. - Don’t be afraid to experiment and see how different statements interact.
- Utilize online resources and tutorials for further learning and practice.
5. Next Steps:
- Explore advanced conditional statements like nested
if
and ternary operators. - Learn about control flow loops for repeated execution based on conditions.
- Keep building your coding skills with projects and challenges!
Recall that conditional
statements are used to run pieces of code based on whether the condition
is either true or false. Okay, let me demonstrate this now with
a simple example using a variable and an, if else statement. Additionally, we learn how to deal
with cases where we have multiple, if else, if conditions. For example, the if else statement
can be used when you want to execute code based on a certain condition
being either true or false. But what if you have five conditions or
even ten? Well, you could use
multiple lines of else If. There is another way to do this,
using something called a switch statement. Okay, let me demonstrate this now with
an example of when to use else if, and when to use the switch statement. So, I have VS code open here and noticed that I have pasted in
an example of an if else statement. First, on line three here I’ve assigned
the value of 50 to the variable result. Then on line five I’m checking if
the result Is greater than 40. If this returns the Boolean value of true, my code will console log
the words you pass the test. After that, on line seven,
I specify the else block which will run when the if condition
returns false instead of true. In that case, I use console.log to output,
you did not pass the test. Okay, so now let’s run this code, and as expected I get the output
of you pass the test. This happened because the statement
50 is greater than 40 in the if condition returned true, and
its associated block of code was executed. Now, let me change the value of the result
variable to say 30 and rerun the code. This time I was notified that
I did not pass the test. This was because the condition 30 is
greater than 40 was evaluated and returned false. The code was skipped inside the if block,
instead, the code inside the else block was run. My code works well because I’m
checking a binary condition here, but what if there are more options? In that case, I’ll need to
cover all these possibilities. Let me switch tabs to demonstrate
this using else if statements. Okay, so notice that I have
a variable named place and it’s assigned to a string
with the value of first. Next, notice my code contains
four conditional statements. The first, is an if statement that
checks if the value of the variable place equals the string value of first. If this is true then a message of
gold will output to the console. As there are three more conditions, the
next one needs to use an else if block. This time I’m checking if the value
stored in the place variable equals the string value of second. Once again, if this is true a message
of silver will output to the console. Notice lines nine and ten, this code is
another else if block that checks for a value of 3rd and
outputs the message of bronze. And this process would keep repeating for
as many conditions as needed. Finally, if no condition is met, I have
a catch all else statement at the end. This is crucial because if the conditional
checks for the values first, second or third are not satisfied, the else block
will run and output the text, No medal. Okay, so this code looks good to me. Let me run it to test the output. Notice the word gold is outputted,
while this method is correct, it can become a bit unmanageable
when there are multiple conditions. For example, say you had to
evaluate ten conditions, luckily, there is another statement at our disposal
and this is called the switch statement. Let me switch tabs again and
now notice the code. So, here I have a switch example, but I
want to examine these files side by side. So, let me click on the tab of
the switch statement file and I’ll drag it around until I
find a good place for it. That will allow me to compare the code. Let’s adjust this a little bit more and
clear the output of the console. Okay, so you may notice that
the syntax is significantly different by Inspecting these two files. If I run the switch statement
code here I get the same result, the word Gold is output. Also, if I change the value of
place variable to say fourth, the default case will be run and the text,
No medal, will output to the console. The if else if,
else example code acts precisely the same. So, here when I update
the variable place to fourth, the same thing happens,
the words, No medal are locked. Congratulations, you have now learned
about conditional statements using the if and else. You’ve also learned how to streamline
multiple conditions using the switch statement. If you would like to learn more about
conditional statements and operators, there is a link to an additional
reading at the end of this lesson.
Reading: Conditional examples
Reading
In this reading, you will learn when to use the if else statement and when to use the switch statement.
Both if else and switch are used to determine the program execution flow based on whether or not some conditions have been met.
This is why they are sometimes referred to as flow control statements. In other words, they control the flow of execution of your code, so that some code can be skipped, while other code can be executed.
At the heart of both flow control structures lies the evaluation of one or more conditions.
Generally, if else is better suited if there is a binary choice in the condition.
For example, in plain English: if it’s sunny, wear sunglasses. Otherwise, don’t.
In this case, using an if statement is an obvious choice.
When there are a smaller number of possible outcomes of truthy checks, it is still possible to use an if else statement, such as:
if(light == "green") {
console.log("Drive")
} else if (light == "orange") {
console.log("Get ready")
} else if (light == "red") {
console.log("Dont' drive")
} else {
//this block will run if no condition matches
console.log("The light is not green, orange, or red");
}
However, if there are a lot of possible outcomes, it is best practice to use a switch statement because it is easier less verbose. Being easier to read, it is easier to follow the logic, and thus reduce cognitive load of reading multiple conditions.
Nevertheless, this is not a rule set in stone. It is simply a stylistic choice.
To reinforce this point, here’s an example of the earlier if else conditional statement, using the switch syntax:
//converting the previous if-else example with switch-case
switch(light) {
case 'green':
console.log("Drive");
break;
case 'orange':
console.log("Get ready");
break;
case 'red':
console.log("Don't drive");
break;
default:
//this block will run if no condition matches
console.log('The light is not green, orange, or red');
break;
}
Reading: Exercise: Practice conditional statements
Reading
Introduction
In this exercise, you will practice working with if else statements. By the end of this exercise, you will be able to write an if else statement that determines your source of income based on your age. You will also be able to write a switch statement that determines your evening routine based on the day of the week.
Complete the following steps to create: Are You Old Enough?
- Declare a variable age using the var keyword and set it to the number 10.
- Add an if statement that checks if the value of the age variable is greater than or equal to the number 65. Inside the if block, console.log the sentence: “You get your income from your pension”.
- Add an “else if“, where you’ll check if the value of the age is less than 65 and greater than or equal to 18. Inside this “else if” block, type “console.log” and then “Each month you get a salary”.
- Add another “else if“, and this time check if the value of the age is under 18. Inside the “else if” block, “type console.log” and then “You get an allowance”.
- Add an “else” statement to capture any other value. Inside the block, type “console.log” and then “The value of the age variable is not numerical”.
Try adjusting the age and executing the program to see how it will affect the output.
Code the days of the week program as a switch statement
- On the next line, define a new variable, name it day, and set its value to “Sunday”.
- Start coding a switch statement, passing the day variable as the expression to evaluate.
- Inside the switch, add cases for every day of the week, starting with ‘Monday’, and ending with ‘Sunday’. Make sure to use string values for days. Inside each case, for now, just add a console.log(‘Do something’), and add a break; on the line below.
- At the very bottom of the switch statement, add the default case and add a console.log(‘There is no such day’).
- Finally, update the console.log calls for each case, based on whatever activity you have on each of the days.
Tips
- If you need to make sure that multiple conditions are true in an if statement, you can do so using the && operator
- In JavaScript, the correct syntax of the “greater than or equal to” operator is: >=.
- Don’t forget to add a break at the very end of each case in a switch statement.
Note: You can find solutions in a separate reading (following this one)
var age = 10
if (age >= 65 ) {
console.log("You get your income from your pension")
} else if ( age < 65 && age >= 18 ) {
console.log("Each month you get a salary")
} else if ( age < 18) {
console.log("You get an allowance")
} else {
console.log("The value of the age variable is not numerical")
}
You get an allowance
Reading: Solutions: Practice conditional statements
Reading
Solutions to the task – Are you old enough?
Step 1:
Declare a variable age using the var keyword and set it to the number 10.
var age = 10;
Step 2:
Add an “if” statement that checks if the value of the age variable is greater than or equal to the number 65. Inside the if block, type “console.log” and “You get your income from your pension”.
var age = 10;
if (age >= 65) {
console.log('You get your income from your pension')
}
Step 3:
Add an “else”, followed with an “if”, where you’ll check if the value of age is less than 65 and greater than or equal to 18. Inside this if block type “console.log” and “Each month you get a salary”.
var age = 10;
if (age >= 65) {
console.log('You get your income from your pension')
} else if (age < 65 && age >= 18) {
console.log('Each month you get a salary')
}
Step 4:
Add another “else if”, and this time check if the value of the age is under 18. Inside the if block, type “console.log” and “You get an allowance”.
var age = 10;
if (age >= 65) {
console.log('You get your income from your pension')
} else if (age < 65 && age >= 18) {
console.log('Each month you get a salary')
} else if (age < 18) {
console.log('You get an allowance')
}
Step 5:
Add an “else” statement to capture any other value. Inside the block, type “console.log” and “The value of the age variable is not numerical”.
var age = 10;
if (age >= 65) {
console.log('You get your income from your pension')
} else if (age < 65 && age >= 18) {
console.log('Each month you get a salary')
} else if (age < 18) {
console.log('You get an allowance')
} else {
//this block will run if no condition matches
console.log('The value of the age variable is not numerical')
}
Solutions to the Days of the Week program
Step 1:
On the next line, define a new variable, name it day, and set its value to Sunday.
var day = 'Sunday';
Step 2:
Start coding a switch statement, passing the day variable as the expression to evaluate.
var day = 'Sunday';
switch(day) {
//add your conditions
}
Step 3:
Inside the switch, add cases for all the days of the week, starting with ‘Monday’, and ending with ‘Sunday’. Make sure to use string values for days. Inside each case, for now, just add a console.log(‘Do something’), and add a break; on the line below.
var day = 'Sunday';
switch(day) {
case 'Monday':
console.log('Do something');
break;
case 'Tuesday':
console.log('Do something');
break;
case 'Wednesday':
console.log('Do something');
break;
case 'Thursday':
console.log('Do something');
break;
case 'Friday':
console.log('Do something');
break;
case 'Saturday':
console.log('Do something');
break;
case 'Sunday':
console.log('Do something');
break;
}
Step 4:
At the very bottom of the switch statement, add the default case and add a “console.log”(‘There is no such day’).
var day = 'Sunday';
switch(day) {
case 'Monday':
console.log('Do something');
break;
case 'Tuesday':
console.log('Do something');
break;
case 'Wednesday':
console.log('Do something');
break;
case 'Thursday':
console.log('Do something');
break;
case 'Friday':
console.log('Do something');
break;
case 'Saturday':
console.log('Do something');
break;
case 'Sunday':
console.log('Do something');
break;
default:
//this block will run if no condition matches
console.log('There is no such day');
}
Step 5:
Finally, update the console.log calls for each case, based on whatever activity you have on each of the days.
var day = 'Sunday';
switch(day) {
case 'Monday':
console.log('Read a book');
break;
case 'Tuesday':
console.log('Watch a movie');
break;
case 'Wednesday':
console.log('Read a book');
break;
case 'Thursday':
console.log('Play basketball');
break;
case 'Friday':
console.log('Socialize');
break;
case 'Saturday':
console.log('Chill');
break;
case 'Sunday':
console.log('Have barbecue');
break;
default:
//this block will run if no condition matches
console.log('There is no such day');
}
Video: Looping constructs
Key Points:
- Loops: Essential for repeating code blocks until a condition is met.
- Counter Variable: Tracks loop progress and prevents infinite loops.
- Types of Loops:
- For Loop: Structured loop with counter initialization, condition, and increment/decrement within its syntax.
- While Loop: Similar to the for loop, but counter setup and incrementing are done outside the loop’s body.
- Best Practices:
- For loops are often preferred for beginners due to their organized structure.
- Always remember to update the counter to avoid infinite loops.
Additional Notes:
- Nested loops (loops within loops) are also possible for more complex tasks.
- The choice between for and while loops depends on specific coding needs and preferences.
Remember: Loops are powerful tools for automating repetitive tasks in JavaScript, making your code more efficient and concise. Understanding their principles and proper use is crucial for effective programming.
Mastering the Art of Loops:
In JavaScript, loops are like magic wands that let you repeat blocks of code effortlessly. They’re essential for automating tasks and making your code more concise and efficient. Let’s dive into the two most common types:
1. The For Loop: Structured Repetition:
- Syntax:
JavaScript
for (initialization; condition; increment/decrement) {
// code to be repeated
}
- Breakdown:
- Initialization: Sets up the starting value of the counter variable (e.g.,
let i = 0;
). - Condition: Determines how long the loop runs (e.g.,
i < 10;
). - Increment/Decrement: Updates the counter after each iteration (e.g.,
i++;
ori--;
).
- Initialization: Sets up the starting value of the counter variable (e.g.,
- Example:
JavaScript
for (let i = 1; i <= 5; i++) {
console.log("Number:", i);
}
2. The While Loop: Flexible Control:
- Syntax:
JavaScript
while (condition) {
// code to be repeated
}
- Breakdown:
- Condition: The loop continues as long as this condition remains true.
- Counter: You must manually initialize and update the counter within the loop’s body.
- Example:
JavaScript
let count = 0;
while (count < 3) {
console.log("Counting:", count);
count++;
}
Key Points:
- Choose
for
loops for structured, predictable repetitions. - Opt for
while
loops when you need more flexible control over the loop’s continuation. - Always ensure the condition will eventually become false to avoid infinite loops.
- Use
break
to exit a loop early andcontinue
to skip to the next iteration.
Additional Tips:
- Indent code within loops for readability.
- Use meaningful variable names for counters.
- Test your loops thoroughly to ensure they run as intended.
- Explore nested loops (loops within loops) for more complex tasks.
Practice Makes Perfect:
- Experiment with different loop scenarios to solidify your understanding.
- Try solving coding challenges that involve loops.
- Explore real-world examples of loop usage in JavaScript projects.
You need to execute repeated blocks of JavaScript code until a certain condition is satisfied. Can you perform this action using loops?
Yes
Yes, JavaScript developers use loops to continually execute repeated blocks of code until a certain condition is satisfied.
In our everyday life, there are times when
we have to repeat some activity again and again. For example, closing each
button when putting on a shirt, washing a stack of
plates one by one, or counting down from ten to one before singing
Happy New Year. Repetitive tasks
are effective life, and sometimes we also need to do these in our JavaScript code. In this video, you
will learn about looping constructs
and how they can be used to perform
repetitive tasks. Recall the conditional
IF statement that executes a block of code if
a certain condition is met, this sequence only runs once. What if you needed to
do this multiple times? Well, to do this you need to
do something called loops. In JavaScript, developers
use loops to continually execute repeated blocks of code until a certain
condition is satisfied. Loops are similar to conditionals
and that a condition must be satisfied in order
for the code to execute. But loops have an
additional parameter, which has many names. But for the moment,
you can think of this as an incrementer
or loop counter. To understand why the counter
variable is so important, let’s consider a
real-life situation. We’re counting down from 10-1, before singing Happy New Year. In other words, only after
we have completed the count, we can start singing. Those our countered needs
to be a specific value, a one and only after that, we can sing a song. In JavaScript, the
counter can be any variable or any number
but in programming, it’s common to use the letter I. The role of the counter is
vital here, as, without it, your loop will not
know neither when to start nor when to terminate, and could run indefinitely. This is known as
an infinite loop. For example, say you
wanted to program a count sequence like 1,2,3. You could do this just by
using the console.log method. However, we are essentially performing the same
activity here. The only difference is
that we’re changing the number that is being
logged to the console. Using a loop, we could
perform the same task more efficiently and
using less lines of code. While this might seem like a minimal gain for
counting to three, imagine counting to 100. Using a loop, you
can achieve this with the exact same
three lines of code. You just have to
update the condition. There are many types of loops, such as the for loop, the while loop, and
the nested loop. You will learn about
the nested loops later in this lesson. For now, let’s explore
the far end while loop. First is the for-loop, which is used to loop a block of code a certain number of times. The for-loop is a
structured loop with a specific conditional structure where a counter
variable must be set. Then a condition must be
specified and finally, the counter must be incremented. This can either
be an increase or a decrease depending
on your needs. The while loop is
similar to the for-loop. It will also run for as long as the condition
returns true. However, the start
counter is set outside of the while loop and
the incrementing is done inside the loop’s body. Congratulations. In this video, you learned about
loop construction using the far and while loop. While you can achieve the
same results using either a for or while loop as
a budding developer, you might find it easier
to work with the for-loop. This is because the loop is self-contained with all the
loop’s logic in one place. Additionally, always remember to update the counter value, otherwise, the loop
might loop forever.
Video: For loop
Key Points:
- For loops automate repetitive tasks.
- Basic structure:
for (initialization; condition; increment/decrement) { ... }
- Counter variable (often
i
):- Tracks loop progress.
- Needs initialization, condition, and increment/decrement.
- Exit condition:
- Prevents infinite loops by specifying when to stop.
- Loop body:
- Contains code to be repeated.
- Decrementing:
- Use
i--
to count down.
- Use
Example (countdown):
JavaScript
for (let i = 10; i > 0; i--) {
console.log(i);
}
console.log("Happy New Year!");
Additional Tips:
- Experiment with different counter values and conditions.
- Use meaningful variable names.
- Test your loops thoroughly.
Remember:
- For loops are essential for efficient code in JavaScript.
- Practice creating them to solidify your understanding.
Mastering the For Loop: Your Repetition Champion
In JavaScript, the for loop is your go-to tool for repeating code blocks with precision. It’s like a trusty drill that can automate tasks and make your code more concise and efficient. Let’s explore its mechanics:
1. Anatomy of a For Loop:
- Structure:
JavaScript
for (initialization; condition; increment/decrement) {
// code to be repeated
}
- Breakdown:
- Initialization: Sets the starting value of the counter variable (e.g.,
let i = 0;
). - Condition: Determines how long the loop runs (e.g.,
i < 10;
). - Increment/Decrement: Updates the counter after each iteration (e.g.,
i++;
ori--;
).
- Initialization: Sets the starting value of the counter variable (e.g.,
2. How It Works:
- Initialization: The counter variable is set to its starting value.
- Condition Check: The condition is evaluated. If true, the code within the loop body executes.
- Code Execution: The code within the curly braces runs.
- Increment/Decrement: The counter variable is updated.
- Repeat: Steps 2-4 repeat until the condition becomes false.
3. Examples:
- Counting from 1 to 5:
JavaScript
for (let i = 1; i <= 5; i++) {
console.log(i);
}
- Counting Down from 10 to 1:
JavaScript
for (let i = 10; i >= 1; i--) {
console.log(i);
}
- Printing Even Numbers from 2 to 10:
JavaScript
for (let i = 2; i <= 10; i += 2) {
console.log(i);
}
4. Key Points:
- Choose meaningful variable names for counters.
- Always ensure the condition will eventually become false to avoid infinite loops.
- Use
break
to exit a loop early andcontinue
to skip to the next iteration. - Indent code within loops for readability.
- Test your loops thoroughly to ensure they run as intended.
5. Practice Makes Perfect:
- Experiment with different loop scenarios to solidify your understanding.
- Try solving coding challenges that involve for loops.
- Explore real-world examples of for loop usage in JavaScript projects.
By mastering for loops, you’ll unlock a new level of control and efficiency in your JavaScript coding journey!
Let’s say you want to
code a count from 1-3, and then say go as
if we’re erasing. You could do this by logging each step to the console for 1, 2, 3 and go. While this method works, imagine a situation where
you have to count from 1-10, 1-100, or even more, where we have to type the
console dialog method a 100 times. Luckily there’s a more
efficient way to do this by using something
called a for-loop. Let me clear my
counsel and paste in an example of how to
do this using a for-loop. First is the declaration
using the for keyword. This declaration consists of something known as the counter. The counter is a
variable which is typically named i for iterator, but you could use any
variable name you want. The counter has three conditions for the for-loop to function. First, the start count
value must be assigned, in this example it’s one. The second condition is
the end-count value. This specifies how many times the loop will
iterate or run. In this example, the condition is that
the value of i must be less than or equal to
three for the loop to run. The final part is
the incrementor which changes the value
of i on each loop. It’s set to increase the number stored in the variable i by one, each time the code
inside the loop runs. You may have learned the
technique i equal to i plus 1, but you can also use the
syntax i plus plus as another way to increase
the value of i by one. If you do not specify
how the value of i should be increased
after each loop, the for loop will run forever, as i would always
be less than three. You need something known
as an exit-condition. The exit-condition works with the incrementor to
prevent the loop from running forever by specifying at which value to
terminate the loop. In this example, the
loop terminates when the value of i is
greater than three. The loop will terminate when the exit condition
returns false. In other words, until the
value of i equals to 4. Since 4 less than or greater
than 3 returns false, the for-loop will exit
and JavaScript will continue reading and
running code below it. The final part of
the for-loop is the loop-body which is
enclosed in curly braces. This contains the
block of code that I want to run on each
loop-iteration. In this example, I want
to print the value of i to the console using
console-dialog method. Notice that this code outputs the same result as
displayed earlier. Well, let’s see in an action. Great, you’ve just created
your first for loop. There are different ways that
you can work with for loop. For example, I could
start my count at 10 and set the value of i
to be greater than zero. Now, instead of incrementing the value of i with plus plus, I can decrement with
the value minus minus. This is essentially
like counting backward. Instead of saying go, we might say Happy New Year. I press, “Enter,” and
there is the result. The countdown outputs from
10-1 and the greeting, Happy New Year is displayed. Let’s break down
what’s happening here. The console-dialog part of
the for-loop was repeated 10 times until the value
of i reached zero. Once the value of
i reached zero, the condition i greater than 0 was no longer met
and the loop exited. Remember, a for-loop is a way to automate repetition
in JavaScript. Why not try creating one in your own code to
repeat some code.
Video: While loop
Key Points:
- While loops repeat code as long as a condition is true.
- Basic structure:
while (condition) { ... }
- Counter initialization:
- Set outside the loop before it starts.
- Condition:
- Checked before each loop iteration.
- Loop stops when it becomes false.
- Loop body:
- Contains code to be repeated.
- Manual counter update:
- Decrement (or increment) inside the loop body to control progress.
Example (countdown):
JavaScript
let counter = 3;
while (counter > 0) {
console.log(counter);
counter--;
}
console.log("Happy New Year!");
Differences from for loops:
- Counter: Set outside the loop in while loops, within the for loop syntax.
- Condition: Only exit condition in while loops, initialization and increment/decrement also specified in for loops.
Remember:
- While loops offer flexibility but require careful counter management.
- Choose the loop type that best suits your coding needs.
Additional Tips:
- Use meaningful variable names for counters.
- Ensure the condition will eventually become false to avoid infinite loops.
- Test your loops thoroughly.
Unleashing the While Loop: Your Conditional Repetition Master
While loops offer a flexible way to repeat code blocks in JavaScript, giving you more control over the process. Let’s dive into their mechanics:
1. Anatomy of a While Loop:
- Structure:
JavaScript
while (condition) {
// code to be repeated
}
- Breakdown:
- Condition: A Boolean expression that determines whether the loop continues.
- Loop Body: Contains the code that executes as long as the condition remains true.
2. How It Works:
- Condition Check: The condition is evaluated. If true, the code within the loop body executes.
- Code Execution: The code within the curly braces runs.
- Repeat: Steps 1-2 repeat until the condition becomes false.
3. Key Points:
- Counter Initialization: Set the counter variable outside the loop before it starts.
- Manual Counter Update: Increment or decrement the counter within the loop body to control progress.
- Exit Condition: Ensure the condition will eventually become false to avoid infinite loops.
- Indentation: Indent code within the loop for readability.
- Testing: Thoroughly test your loops to ensure they run as intended.
4. Examples:
- Countdown from 3 to 1:
JavaScript
let counter = 3;
while (counter > 0) {
console.log(counter);
counter--;
}
console.log("Happy New Year!");
- Reading User Input Until “Quit”:
JavaScript
let input = "";
while (input !== "quit") {
input = prompt("Enter a word (or 'quit' to exit):");
console.log("You entered:", input);
}
5. Practice Makes Perfect:
- Experiment with different while loop scenarios to solidify your understanding.
- Try solving coding challenges that involve while loops.
- Explore real-world examples of while loop usage in JavaScript projects.
6. When to Use While Loops:
- When you need more flexible control over the loop’s continuation than a for loop provides.
- When the number of iterations isn’t known beforehand.
- When you want to repeat code based on user input or other unpredictable factors.
By mastering while loops, you’ll expand your JavaScript toolbox and create more dynamic and adaptable code!
In this video you will learn
about another type of loop, the while loop and use it to code a
countdown to the happy new year greeting. The while loop is quite similar to the for
loop but they’re not exactly the same. The first major difference
is the counter value. With a while loop this is set before
the loop and must be clearly defined. Let me demonstrate this now. First, I create a variable called
counter and set its value to 3. Next I want you to know about
the second major difference. This is that you only need to specify
the exit condition in the parentheses of the loop declaration or put differently, we just give JavaScript
an expression to check. If that expression returns true
JavaScript will then run the code inside the while loop. In this example our condition will
be counter is greater than 0. Since the counter value of 3 Is
greater than 0 it returns true. So to construct the while loop
I typed the word while and then the condition inside the parentheses,
this is counter greater than 0. Next, inside the wild loops code
block I need to tell it what to do. In this example I want to run
the console.log method to output the value of the counter, then I need to
decriminalize my counter by a value of 1. This means that the first time JavaScript
starts running the line of code with the while loop declaration it checks
the value of the counter variable. If the counter value is greater than 0 and
it is, it will run the code inside the wild loop
then it will output the current value of the counter variable to
the console which is the number 3. Next, it will calculate the value of
counter- 1, that is 3- 1 which is two. It will then update the counter variable
by assigning the number two as its new value. Finally it will return to
the whiles condition and check if the counter value is greater
than 0, that is if two is greater than 0. Since it is, it will go into
the while loops code block again and output the counters current
value which is two. Then it will update it again by assigning
the result of 2- 1 as the updated value of the counter variable. Now since it’s reached the end of
the block, JavaScript will go back up and confirm that it’s true that 1 is greater
than 0 then go inside the while loops body again, output the value of 1 and
update the counter to 1- 1. Since it’s reached the end of
the loop’s body, it will go back up and check if 0 is greater than 0 and since it isn’t it will not run
the code inside the while loop again. Instead any code under the closing
curly brace of the while loop will run. To demonstrate this I add another line of
code under this closing curly brace and console log the string,
Happy New Year and that’s it. Congratulations, you have now learned
how to create and run a while group. Why don’t you give it a try? Loops are a common way to
automate code repetition. If you would like to learn more about
the specific use of loops there is an additional reading at
the end of this lesson.
Reading: Exercise: Repetitive tasks with loops
Reading
In this exercise, you will practice writing “for” and “while” loops.
Task 1
Write a “for” loop that will perform exactly the same repetitive code as this:
for (var i = 1; i <= 5; i++ ){
console.log(i)
}
console.log('Counting completed!')
console.log(1)
console.log(2)
console.log(3)
console.log(4)
console.log(5)
console.log('Counting completed!')
1
2
3
4
5
Counting completed!
1
2
3
4
5
Counting completed!
Task 2
Write a “for” loop that will perform exactly the same repetitive code as this:
for (var i = 5; i > 0; i--){
console.log(i)
}
console.log('Countdown finished!')
console.log(5)
console.log(4)
console.log(3)
console.log(2)
console.log(1)
console.log('Countdown finished!')
5
4
3
2
1
Countdown finished!
5
4
3
2
1
Countdown finished!
Task 3
Write a “while” loop that will perform exactly the same repetitive code as this:
var i = 1
while (i < 6){
console.log(i)
i ++
}
console.log('Counting completed!')
console.log(1)
console.log(2)
console.log(3)
console.log(4)
console.log(5)
console.log('Counting completed!')
1
2
3
4
5
Counting completed!
1
2
3
4
5
Counting completed!
Note: Name your increment variable i. Update the variable in the while loop using i++.
Task 4
Write a “while” loop that will perform exactly the same repetitive code as this:
var counter = 5
while (counter > 0){
console.log(counter)
counter --
}
console.log('Countdown finished!')
console.log(5)
console.log(4)
console.log(3)
console.log(2)
console.log(1)
console.log('Countdown finished!')
5
4
3
2
1
Countdown finished!
5
4
3
2
1
Countdown finished!
Note: In the while loop, decrement the value of i using: i = i – 1.
Task 5
Write a “while” loop that will perform exactly the same repetitive code as this:
var year = 2018
while (year < 2023){
console.log(year)
year ++
}
console.log(2018)
console.log(2019)
console.log(2020)
console.log(2021)
console.log(2022)
2018
2019
2020
2021
2022
2018
2019
2020
2021
2022
Reading: Repetitive tasks with loops (solutions)
Reading
Here are the solutions to the for and while loop exercise.
Task 1
for (var i = 1; i <= 5; i++) {
console.log(i);
};
console.log('Counting completed!');
1
2
3
4
5
Counting completed!
Task 2
for (var i = 5; i > 0; i--) {
console.log(i);
};
console.log('Countdown finished!');
5
4
3
2
1
Countdown finished!
Task 3
var i = 1;
while (i < 6) {
console.log(i);
i++;
};
console.log('Counting completed!');
1
2
3
4
5
Counting completed!
Note: Name your increment variable i. Update the variable in the while loop using i++.
Task 4
Write a “while” loop that will perform the exact same repetitive code like the one below:
var i = 5;
while (i > 0) {
console.log(i);
i = i - 1;
};
console.log('Counting completed!');
5
4
3
2
1
Counting completed!
Note: In the while loop, decrement the value of i using: i = i – 1.
Task 5
Write a “while” loop that will perform the exact same repetitive code like the one below:
var year = 2018;
while (year < 2023) {
console.log(year);
year++;
};
2018
2019
2020
2021
2022
Video: Nested loops
Purpose:
- To perform multiple tasks simultaneously within code.
- To iterate through multiple sets of data or conditions.
Structure:
- Involve placing one loop inside the body of another loop.
- The outer loop controls the larger iteration, while the inner loop handles subtasks within each iteration.
Example:
- Generating a two-week plan with days and weeks: The outer loop iterates over weeks, the inner loop over days within each week.
Performance Considerations:
- Use with caution as excessive nesting can impact code performance.
- Strive for efficiency to optimize resource usage.
Best Practices:
- Employ descriptive variable names for clarity when learning.
- Consider using single-letter variables (i, j) for standard practice and readability within the development community.
Common Use Cases:
- Handling multiple data sets or tasks concurrently.
- Sorting data (e.g., from highest to lowest).
- Generating complex outputs involving multiple levels of repetition.
Understanding Nested Loops:
- Purpose: To execute multiple loops within each other, enabling you to handle multiple sets of data or tasks concurrently.
- Structure: Like Russian dolls, one loop (inner loop) resides within the body of another loop (outer loop).
- Example: Imagine iterating through months within each year. The outer loop controls years, while the inner loop handles months within each year.
Creating Nested Loops:
- Outer Loop:
- Use a
for
loop to initiate the outer iteration. - Example:
for (let year = 2023; year < 2025; year++) {
- Use a
- Inner Loop:
- Within the outer loop’s body, create another
for
loop for the inner iteration. - Example:
for (let month = 6; month < 9; month++) {
- Within the outer loop’s body, create another
- Code Inside Loops:
- Place your code within the inner loop’s body to execute for each combination of outer and inner loop values.
- Example:
console.log(
– ${month});
- Closing Loops:
- Use closing curly braces to end each loop.
Example: Outputting Summer Months Over Two Years:
JavaScript
for (let year = 2023; year < 2025; year++) {
console.log(year);
for (let month = 6; month < 9; month++) {
console.log("-- ${month}");
}
}
Key Points:
- Clarity: Use descriptive variable names when learning, then consider single-letter variables (i, j) for standard practice.
- Performance: Nested loops can impact performance. Use efficiently to optimize resource usage.
- Common Use Cases:
- Handling multiple data sets or tasks concurrently.
- Sorting data (e.g., highest to lowest).
- Generating complex outputs involving multiple levels of repetition.
Practice Tips:
- Experiment with different scenarios to solidify your understanding.
- Break down nested loops into smaller steps to grasp their logic.
- Visualize the code’s execution to follow the flow.
- Explore various use cases to appreciate their versatility.
What if you need
your code to perform more than one task
at the same time? Maybe you need to
process data set A, but at the same time
also process data set B. In cases like this, you can use nested loops. You might already be
familiar with the for loop, which is used for
instructing your code to perform the same task
over and over again. But with JavaScript, it’s
possible to nest loops within other loops so that multiple tasks can be
performed at once. There can be multiple
levels of nesting too. Let’s now examine a
practical example where you might
use a nested loop. Suppose you are creating a two-week plan for the
days Monday to Friday, you need to output each day number and the
week it’s associated to. You have five days for week
1 and five days for week 2. Using a nested loop is the perfect way to
achieve this output. Let me break it down for you now using an example with for loops. If we recall our example, we have two categories;
weeks and days. The first loop, also
known as the outer loop, will loop over the weeks. An increment counter
of 2 is required, and this is created with
a variable named i. Then the nested loop
will loop over the days. To do this, another increment
counter is required, and this is created with
a variable named j. Finally, the console log
method is required to output the text with the values
of i and j to the console. This code outputs
10 lines, week 1, and each day from 1-5, and then the same for week 2. However, you need to take
care not to overdo it as multiple levels of nested loops are not
very performant. In other words, the more
nested loops there are, the slower your code will run. Let’s now explore an example
where you will output code using nested loops to display the summer
months over two years. I’m back in my
browser’s console and I start by pasting in a
for loop declaration. Notice this specifies the
year variable as 2023 and the exit condition
when the comparison of year is less than
2025 returns false. I’ve also set the year’s value to increase by one on each loop. Essentially, I’ve
coded this loop twice. Next, I type console.log in the loop body and place the variable year
inside the parenthesis. I expect the output to
display 2023 and 2024. I run the for loop to confirm that this is the
case, and indeed, the values 2023 and 2024
are logged to the console. This is a process that you
are already familiar with. Now I want to demonstrate
a nested loop, and to do that, I need to add
another loop inside the body of the first for loop. This will also be a for loop. This time I type for
(var month equal 6, month less than 9, and month plus, plus). What I’m doing here is counting
only the summer months. The summer months
are usually June, July, and August in the
Northern Hemisphere. That’s months 6, 7, and 8. Notice that the counter will
start at month 6 and it will keep checking if
the numbers stored in the month variable
are less than 9. On each subsequent loop, the value stored in the multi-variable
will increase by 1. Effectively, it’s going
to go through months 6, 7, and 8. After it runs these three loops, it’s going to stop. Now I type console.log in
the body of the inner loop. To make sure that I showed
that this is nested, I’m going to add
several dash characters and then the month variable. Now, when I run this code, the outer loop will
run for the first time and it will set the value of
the year variable to 2023. Then console log that number, and then go into the code of
the inner loop and run it. Once inside the code
of the inner loop, I can expect the
code to run three times and output dashes 6, dashes 7, and dashes 8. The inner loop will then exit, and the code will move back to the outer loop to begin
the next loop cycle. When this starts, the
value of the year variable has been increased
by one to 2024. This still satisfies
the condition of year is less than 2025. The code logs the year and
proceeds to the inner loop. JavaScript will
go into the inner for loop again and rerun it. Once again, it will output 6, 7, and 8 again. This code will continue
this sequence display in the year 2024 and the final
three months of summer. Let me run the code now. Success. The code produced
my predicted output. Before I end this video, let me demonstrate how to
simplify the for loop. Instead of using these
long variable names, I can just use i
instead of the year, and I can use j
instead of the month. This makes the code
easier to read. It might seem harder to
understand because I’m using i and j instead of more
descriptive names. But these variable names
are standard practice in the development
community and are considered a best
practice to use. You have now learned about nested loops and the
reason to use them. It’s important to
remember that while nested loops are an
option for developers, they can be resource-intensive. Nested loops can be used in instances where you need
automated repetition of code, for example, sorting numbers
from highest to lowest. A good developer writes code efficiently to
maximize resources, and you are on your way
to becoming one of them.
Reading: Loops and nested loops
Reading
Let’s say I want to output a custom multiplication table.
This is a perfect use case scenario for nested loops.
The outer loop’s counter variable will act as the first number to be multiplied, and the inner loop counter variable will act as the second number to be multiplied.
Here’s my code:
//single loop
for (var firstNum = 0; firstNum < 2; firstNum++) {
console.log(firstNum);
}
The output of the above code will be:
0
1
This means that my for loop starts at 0 and stops after 1.
So now I can code what will later become the inner loop, whose counter variable will be the second number in this multiplication:
//single loop
for (var secondNum = 0; secondNum < 10; secondNum++) {
console.log(secondNum);
}
This time, the output is:
0
1
2
3
4
5
6
7
8
9
Now’s the time to combine the first and the second loop:
//nested loops - one inside another
for (var firstNum = 0; firstNum < 2; firstNum++) {
for (var secondNum = 0; secondNum < 10; secondNum++) {
console.log(firstNum + ", " + secondNum);
}
}
Now that I’m nesting the second for loop inside the first one, and that I’m console logging the values of both counter variables as the loops are progressing, the output looks like this:
0, 0
0, 1
0, 2
0, 3
0, 4
0, 5
0, 6
0, 7
0, 8
0, 9
1, 0
1, 1
1, 2
1, 3
1, 4
1, 5
1, 6
1, 7
1, 8
1, 9
Now that I have a list of all the numbers that will be multiplied, having the actual result of this multiplication is as easy as updating the console.log() call:
//nested loops - one inside another
for (var firstNum = 0; firstNum < 2; firstNum++) {
for (var secondNum = 0; secondNum < 10; secondNum++) {
console.log(firstNum + " times " + secondNum + " equals " + firstNum * secondNum);
}
}
The output now is:
0 times 0 equals 0
0 times 1 equals 0
0 times 2 equals 0
0 times 3 equals 0
0 times 4 equals 0
0 times 5 equals 0
0 times 6 equals 0
0 times 7 equals 0
0 times 8 equals 0
0 times 9 equals 0
1 times 0 equals 0
1 times 1 equals 1
1 times 2 equals 2
1 times 3 equals 3
1 times 4 equals 4
1 times 5 equals 5
1 times 6 equals 6
1 times 7 equals 7
1 times 8 equals 8
1 times 9 equals 9
This makes for some very interesting combinations.
For example, I can make a custom division table:
//nested loops - one inside another
for (var i = 100; i > 10; i = i - 10) {
for (var j = 10; j > 4; j = j - 5) {
console.log(i + " divided by " + j + " equals " + i / j);
}
}
Here’s the output of the above nested loop:
100 divided by 10 equals 10
100 divided by 5 equals 20
90 divided by 10 equals 9
90 divided by 5 equals 18
80 divided by 10 equals 8
80 divided by 5 equals 16
70 divided by 10 equals 7
70 divided by 5 equals 14
60 divided by 10 equals 6
60 divided by 5 equals 12
50 divided by 10 equals 5
50 divided by 5 equals 10
40 divided by 10 equals 4
40 divided by 5 equals 8
30 divided by 10 equals 3
30 divided by 5 equals 6
20 divided by 10 equals 2
20 divided by 5 equals 4
Feel free to try out some other combinations of nested loop iterations, and see what kind of output you’ll get.
Reading: Uses of loops
Reading
In this reading, we’ll discuss, at a very high level, the reasons to use loops in JavaScript.
Note that we will keep this discussion high-level because there are multiple “pieces of the puzzle” that are still missing from your understanding at this point.
This is why we will not get bogged-down in the detail of syntax and implementation, but instead, simply discuss how and why loops are used in everyday work of JavaScript developers.
Consider the following example: You work as a developer for an online store.
The store is selling letter cubes for toddlers, and the entire “Shop now” section of the site is organized in a layout where each cube on sale is displayed in a simple card component, with an image of the cube, the letter it teaches, a short description, and the price.
Cards are organized in rows, so that each row contains three cards – three different letters.
Each card is a preview of that specific letter cube on sale, and it’s also a link to an entire page, dedicated to providing more info about the cubes, their teaching value, and providing the visitor with a way to complete their checkout process.
Now, here’s a quick question: where would loops fit into displaying this grid of cards showcasing the letter cubes on sale?
To understand just how this works, let me code a basic prototype of how this might work.
Since you still don’t have enough knowledge to display website layouts in browser with the help of JavaScript, for now I’ll have to settle for using a simple string and the console.
Still, this should be a fun exercise.
var cubes = 'ABCDEFG';
//styling console output using CSS with a %c format specifier
for (var i = 0; i < cubes.length; i++) {
var styles = "font-size: 40px; border-radius: 10px; border: 1px solid blue; background: pink; color: purple";
console.log("%c" + cubes[i], styles)
}
Note: In order to have the styles applied, try running this code snippet in your browser’s console.
That’s it, with this simple code, the output in the console shows each letter on a separate line, styled like a letter cube for toddlers.
The code itself should be mostly familiar, except for the cubes.length and the cubes[i] syntax.
Without getting into too many details, here are both code snippets explained as simple as possible.
The cubes.length returns a number. Since cubes is a string of characters the cubes.length gives me the length of the string saved in the variable.
So this gives me the number 7, effectively making my for loop look like this:
var cubes = 'ABCDEFG';
//styling console output using CSS with a %c format specifier
for (var i = 0; i < 7; i++) {
var styles = "font-size: 40px; border-radius: 10px; border: 1px solid blue; background: pink; color: purple";
console.log("%c" + cubes[i], styles)
}
The second piece of code that’s new here is the cubes[i] snippet.
This simply targets each individual letter in the loop, based on the current value of the i variable.
In other words, cubes[i], when i is equal to 0, is: A.
Then, cubes[i], when i is equal to 1, is: B.
This goes on for as many loops my for loop runs – and this is determined by the cubes.length value.
It’s also very versatile, since, if I, for example, decided to change the length of the cubes string, I would not have to update the condition of i < cubes.length, because it gets automatically updated when I change the length of the cubes string.
There are some other ways to store data in JavaScript apps that you haven’t heard about.
But we can use the same approach with those other kinds of data, to achieve results that essentially work on the same principle as the one just described.
Using loops is the essence of the approach taken in developing many different pieces of functionality in software today.
Some additional examples
If I’m coding an email client, I will get some structured data about the emails to be displayed in the inbox, then I’ll use a loop to actually display it in a nicely-formatted way.
If I’m coding an e-commerce site selling cars, I will get a source of nicely-structured data on each of the cars, then loop over that data to display it on the screen.
If I’m coding a calendar online, I’ll loop over the data contained in each of the days to display a nicely-formatted calendar.
There are many, many other examples of using loops in code.
Using loops with data that is properly formatted for a given task is a crucial component of building software.
In the lessons that follow, we’ll learn about different ways of grouping related data and of displaying it on the screen using JavaScript.
When combined with what you’ve already learned about loops, this gives you the skills to build various kinds of user interfaces where there is repetitive information.
Some more specific examples include:
- looping over blog post titles in some structured data, and displaying each blog post title on a blog home page
- looping over social media posts in some structured data, and displaying each social media post based on some conditions
- looping over some structured data on clothing available for sale in an online clothing store, and displaying relevant data for each item of clothing
Now you understand the importance of knowing how to work with loops in JavaScript. In the upcoming lessons, we’ll learn other relevant information which will allow you to be able to do this.
Reading: Exercise: Working with conditionals and loops
Reading
Exercise 1
In this exercise, you will create the code for a for loop, using the counter variable named i starting from 1.
To make the counter increment by 1 on each loop, you will use i++.
The exit condition for the for loop should match the output given below.
Inside the loop, write an if-else statement, which will check the following conditions:
- First, it will check if the value of i is 1. If it is, your code will console log the string “Gold medal”.
- Next, I will check if the value of i is 2. If it is, your code will console log the string “Silver medal”.
- Then, your code will check if the value of i is 3. If it is, it will console log the string “Bronze medal”.
- For all the remaining values of i, your code will console log just the value of i.
Note: The expected console log of the entire code should be as follows.
Gold medal
Silver medal
Bronze medal
4
5
6
7
8
9
10
for (var i = 1; i <= 10; i++){
if (i == 1) {
console.log("Gold medal")
} else if (i == 2){
console.log("Silver medal")
} else if( i == 3){
console.log("Bronze medal")
} else {
console.log(i)
}
}
Gold medal
Silver medal
Bronze medal
4
5
6
7
8
9
10
Exercise 2. Use the completed code from the previous task, but convert the conditionals to a switch statement.
When you code the solution, the output in the console should remain exactly the same as in the previous question.
Note: You’ll need three separate cases for the three medals, and a default case for all other values of the i variable.
for (var i = 1; i <= 10; i++){
switch(i){
case 1:
console.log("Gold medal")
break
case 2:
console.log("Silver medal")
break
case 3:
console.log("Bronze medal")
break
default:
console.log(i)
}
}
Gold medal
Silver medal
Bronze medal
4
5
6
7
8
9
10
Reading: Solution: Working with conditionals and loops
Reading
Answer 1:
for (var i = 1; i <= 10; i++) {
if(i == 1) {
console.log("Gold medal")
} else if (i == 2) {
console.log("Silver medal")
} else if (i == 3) {
console.log("Bronze medal")
} else {
//this block will run if no condition matches
console.log(i)
}
}
Answer 2:
for (var i = 1; i <= 10; i++) {
switch(i) {
case 1:
console.log("Gold medal")
break
case 2:
console.log("Silver medal")
break
case 3:
console.log("Bronze medal")
break
default:
//this block will run if no condition matches
console.log(i)
}
}
Practice Quiz: Knowledge check – Conditionals and loops
Based on the following code, what will print out when the variable i has the value 3 ?
if(i < 5) {
console.log("Hello");
} else {
console.log("Goodbye");
}
Hello
That’s correct! The code inside the if statement will execute because the condition i < 5 is true.
Based on the following code, what will print out when the variable i has the value 1 ?
if(i == 0 && i == 1) {
console.log("Hello");
} else {
console.log("Goodbye");
}
Goodbye
That’s correct! The condition checks if i is equal to 0 AND 1 . Since it is not possible for i to be both values at the same time, the result of this check is false. Therefore, the code inside the else statement will run.
How many times will the following code print the word ‘Hello’?
for (i = 0; i < 2; i++) {
console.log("Hello");
}
2
That’s correct! The loop will run twice based on the condition i < 2 .
How many times will the following code print the word ‘Hello’?
var i = 0;
while(i < 3) {
console.log("Hello");
i++;
}
3
That’s correct! The loop will run 3 times based on the condition i < 3 .
How many times will the following code print the word ‘Hello’?
for (i = 0; i < 2; i++) {
for (var j = 0; j < 3; j++) {
console.log("Hello");
}
}
6
That’s correct! The inner loop will be run twice by the outer loop. Since the inner loop runs 3 times, the console.log will be called 6 times in total.
Based on the following code, what will print out when the variable i has the value 7 ?
if(i <= 5) {
console.log("Hello");
} else if(i <= 10) {
console.log("Goodnight");
} else {
console.log("Goodbye");
}
Goodnight
That’s correct! The code inside the else if statement will execute. The first condition fails because the value of i is greater than 5. The second condition succeeds because the value of i is less than 10.
Based on the following code, what will print out when the variable i has the value 3 ?
switch(i) {
case 1:
console.log("Hello");
break;
case 2:
console.log("Goodnight");
break;
case 3:
console.log("Goodbye");
break;
}
Goodbye
That’s correct! The code for case 3 will run.
Based on the following code, what will print out when the variable i has the value 3 ?
if(i == 2 || i == 3) {
console.log("Hello");
} else {
console.log("Goodbye");
}
Hello
That’s correct! The condition checks if i is equal to 2 OR 3 . Since the value of i is 3 , the code inside the if statement will run.
Video: Module summary: Introduction to JavaScript
This module equipped you with the fundamentals of JavaScript programming. You learned:
- Programming Concepts: What programming is and its role in the modern world.
- JavaScript Basics: What JavaScript is and its importance for web development.
- Developer Interaction: How developers interact with the JavaScript engine to create web experiences.
- Data Storage: Creating and modifying variables with different data types:
- Primitives: Numbers, strings, Booleans, null, undefined, symbol, and bigint.
- Strings: Building and manipulating text data.
- Booleans: Representing true/false values and their operations.
- Numbers: Performing calculations and understanding their limitations.
- Conditional Logic: Using
if-else
statements to control program flow based on conditions. - Repetitive Tasks: Writing
for
loops to automate repetitive tasks.
Congratulations on completing this module! You’ve laid a strong foundation for your JavaScript journey.
This summary highlights the key concepts covered, emphasizing data types, control flow, and loop constructs. It also congratulates the user on their progress, reinforcing a positive learning experience.
You’ve reached the
final video in this lesson on conditionals and loops and the end of the introduction to
JavaScript module. Let’s take a few moments to
recap on what you’ve learned. In this module, you have
learned how to explain what programming is and the role it plays in the modern world, describe what JavaScript is and its value as a web
development tool, describe how developers
interact with the JavaScript engine to
create web experiences, create variables and assign or reassign the values
they contain, identify the seven
primitive data types in JavaScript and how they
differ from one another. Explain what strings are and the syntax for
building them, identify the values of
the Boolean data type, and explain what you can and cannot do with the
numbers datatype. Build if else
statements to create conditional outcomes and build for loops to repeat
repetitive tasks. Congratulations, you have now completed this
module. Great work.
Quiz: Module quiz: Introduction to JavaScript
You can run JavaScript in a web browser’s devtools console.
true
That’s correct! The devtools console is useful for running JavaScript code.
Which of the following are valid comments in JavaScript? Select all that apply.
// Comment 2
/*
* Comment 4
*/
That’s correct! /* and */ are define the beginning and end of multi-line comments.
Which of the following are valid data types in JavaScript? Select all that apply.
string, numbers, booleans, null
Which of the following is the logical AND operator in JavaScript?
&&
That’s correct! && is the logical AND operator used for condition checks.
Which of the following is the assignment operator in JavaScript?
=
How many times will the following code print the word ‘Hello’?
for(var i = 0; i <= 5; i++) {
console.log("Hello");
}
6
That’s correct! ‘i’ starts with the value ‘0’. The condition checks if ‘i’ is less than or equal to ‘5’. Each loop increments ‘i’ by ‘1’. This means that the loop will run 6 times.
What will print out when the following code runs?
var i = 3;
var j = 5;
if(i == 3 && j < 5) {
console.log("Hello");
} else {
console.log("Goodbye");
}
Goodbye
That’s correct! The condition checks if ‘i’ is equal to ‘3’ AND if ‘j’ is less than ‘5’. Since the result of this condition is false, the code inside the else statement will run.
What will print out when the following code runs?
var i = 7;
var j = 2;
if(i < 7 || j < 5) {
console.log("Hello");
} else {
console.log("Goodbye");
}
Hello
That’s correct! The condition checks if ‘i’ is less than ‘7’ OR if ‘j’ is less than ‘5’. Since the result of this condition is true, the code inside the if statement will run.
The result of !false is:
true
Correct! When you add the NOT operator before a boolean value, the returned value is the opposite of the boolean value. Thus, !false is evaluated to true, and !true is evaluated to false.
What does the operator symbol || represent in JavaScript?
The logical OR operator
That’s correct. In JavaScript, the || is the logical OR operator.
Reading: Additional resources for Conditionals and Loops
Reading
Here is a list of resources that may be helpful as you continue your learning journey.
In JavaScript, there is also a shorthand version of writing a conditional statement, known as the conditional (ternary) operator: Conditional (ternary) operator