How to run javascript code

How to run JavaScript? Run JavaScript Files online

Over the years, JavaScript has evolved so much. From being a primary scripting language made for the Netscape Navigator to make websites more dynamic and interactive to the multipurpose and the most loved programming language ever. Today we will look at various ways how to run JavaScript file.

JavaScript is now everywhere. We can now use JavaScript to make Web applications, Server-side applications, Cross-platform Mobile and Desktop applications, Machine Learning, and much more!

We will also look at some online platforms where you can create and run your JavaScript files without setting up a local environment.

Running JavaScript in the browser

This method is the most basic approach using which we can run JavaScript. JavaScript only ran on browsers initially. You can use any web browser for this. But for now, we will stick with Google Chrome.

We can open the browser’s developer console to run JavaScript on your browser. In chrome, to open the developer console, we can follow the following steps,

Читайте также:  Задача 2

Step 1: Right-click on the browser window, and from the bottom of the popup window, click on inspect ,

Step 2: On the side panel opened, click on the console option,

We will see a console window open,

This console is called a REPL or Read Evaluate Print Loop. Here we can write our JavaScript code, which then will be interpreted by the browser’s JavaScript Engine, and the browser will show the output.

Let’s write a code to log ‘Hi from Codedamn’

We will also use this console for displaying the logs and errors generated when we run our JavaScript file in the browsers.

Running JavaScript files in the browser

Although we can run JavaScript directly from the browser console, it’s only suitable for testing small pieces of code. If we wish to write and test some big and complex function, trying it out in the browser console is not a good idea.

The preferred way to implement some big and complex code is to write it in a JavaScript file.

Let’s create a JavaScript file simple-interest.js and open it in our IDE (I’m using VSCode),

Here, we will write a simple function that will compute the simple interest, given the principle, time, and rate. Right after the function declaration, we will call the function and log the result,

function simpleInterest(principle, time, rate) < const si = (principle * time * rate) / 100; return si; > const result = simpleInterest(1000, 1, 10); console.log(result);
Code language: JavaScript (javascript)

We cannot give this file to the browser to execute directly. We must link this file in a .html file and then provide the .html file to the browser. The browser will find the attached JavaScript file from the .html file and execute it.

Let’s create an index.html with some basic HTML and link our JavaScript with it,

html> html> head> title>How to run JavaScript file in browser title> head> body> h1>Running JavaScript file in a browser h1> script src="./simple-interest.js"> script> body> html>
Code language: HTML, XML (xml)

You can click on Go Live at the bottom if you use VSCode and have live-server installed. Otherwise, you can double-click the HTML file from your file explorer.

In both ways, the browser will open the HTML file in a new tab,

If we now open the developer console, we see a log of the calculated Simple Interest ?,

We can create and reference multiple such JavaScript files in our index.html , and the browser will run them, and any output generated will be logged onto the developer console.

What is Node.js?

Node.js is a JavaScript runtime based on Google’s V8 Engine. Ryan Dahl released it as open-source software on 27 May 2009. Since then, Node.js has significantly improved over the years and is now the most popular JavaScript runtime generally used for running JavaScript on the server side.

You can download Node.js for Linux, Mac, and Windows from here.

To run a JavaScript file using Node.js, we use the following command,

node
Code language: Bash (bash)

Running JavaScript files using Node.js

Running a JavaScript file is relatively simple compared to running it in a browser as we won’t need to reference the JavaScript file in a .html file.

Let’s use the same simple-interest.js file we created earlier.

node ./simple-interest.js
Code language: Bash (bash)

NOTE: simple-interest.js is the file path. Since the file is in the root, we can directly reference it with the filename. But If the file is in another directory, we will provide the file’s relative path (or full path).

In the terminal, we will see 100 logged ?,

Codedamn Playgrounds

All the above methods work great. But still, we need a local environment set up to run JavaScript using the above methods.

What if there was some online platform where we could create a development environment and start writing our code in just one click? Well, Codedamn Playgrounds is here for our rescue.

Codedamn Playgrounds needs no introduction. It is one of the best in-browser IDE available for FREE. Use them to code collaboratively with your friends without downloading anything on your computer.

Unlike other online JavaScript platforms, your code runs on the client side. But with Codedamn Playgrounds, all the code you write is run on a real docker-container running a Linux environment. You have full access to the terminal and are developing in a fully configured and isolated Linux Environment for FREE.

What are you waiting for if you don’t have a Codedamn account already? Create an account now.

Running JavaScript on Codedamn Playgrounds

First, log in to your account and navigate the Codedamn Playgrounds.

From here, we can choose from various pre-configured templates to start. These are not limited to JavaScript only. We can run,

Talking about JavaScript, we have the following choices,

Let’s create a simple HTML/CSS/JavaScript playground. Click on the HTML/CSS option and provide a name for your project,

Upon creating a new playground, we will get redirected to the newly created playground,

A simple template is already set up for us, to which we can make more changes or delete all the files and start from scratch.

We will get a Monaco code editor, also used in VSCode. On the right, we get an output window live preview. We can also toggle the browser console from the bottom right to see the logs, warnings, and errors. In the code editor, we get an actual terminal.

Let’s copy the contents of our simple-interest.js file to the script.js file present in the playground and see if everything works properly,

Upon toggling the browser console, we see 100 logged onto the console ?,

Conclusion

This article discussed various ways how to run JavaScript file. We saw how to run our JavaScript code inside the browser and with Node.js. Since these approaches required a local development environment setup, we looked at Codedamn Playgrounds, one of the best free in-browser IDE. Further, we saw how easy it is with Codedamn Playgrounds to create awesome projects without even needing to set up our development environment.

Thank you so much for reading ?

Codedamn is the best place to become a proficient developer. Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.

Unlimited access to all platform courses

100’s of practice projects included

ChatGPT Based Instant AI Help (Jarvis)

Structured Full-Stack Web Developer Roadmap To Get A Job

Exclusive community for events, workshops

Sharing is caring

Did you like what Varun Tiwari wrote? Thank them for their work by sharing it on social media.

Источник

🚀 How to Run JavaScript Code

In order to follow along with this course, you need to know how and where you run your JavaScript code. You have several options to run your first hello world programming:

Open your editor and create a file named index.js .

How to Run JavaScript from the Command Line

Running a JS program from the command line is handled by NodeJS. Start by installing NodeJS on local machine if necessary.

Now simply open the command line in the same directory as the index.js script you created (VS Code will do this automatically with the integrated terminal).

How to Run JavaScript from the Browser

When people think of “JavaScript”, they most often think of a web browser. You can run code in the browser by creating an HTML file that references the script. In our case, we used the defer option, which will execute the JS after the HTML file is finished loading.

Run a script from an HTML file

html>  head>  script defer src="./index.js">script>  head> html> 

Now simply open this HTML file on your local machine and open the developer console (next step) to see the output.

Inspect the Browser Console

In Chrome, you can open the developer console with Ctrl+Shift+J (Windows) or Ctrl+Option+J (Mac), or manually from the settings menu by selecting More Tools -> Developer Tools. The console allows you to run code in the browser, similar to how

Output of the browser console in Chrome

Run JavaScript with a Framework

It is worth mentioning that frameworks like React, Angular, Svelte, etc will take care of the building & running of your app automatically and provide framework-specific tooling and steps for running code. In the real world, you are more likely to use the tooling provided by the framework to run your code, as opposed to the basic methods shown in this couse.

Run JavaScript in a Sandbox

This course uses StackBlitz to run JS code examples in an isolated sandbox in the browser. This is a great option for sharing quick demos and issue reproductions 💡.

Источник

Как запустить JS-код

JavaScript — популярный язык программирования с широким спектром применения. Раньше его использовали в основном для интерактивности веб-страницам: например, для анимации или валидации форм. Сейчас же JS используется еще и во многих других областях: разработка серверных, мобильных приложений и так далее.

Из-за широкого спектра применения JavaScript можно запустить несколькими способами:

Через вкладку «Консоль» в браузере

В большинстве современных браузеров уже есть встроенные механизмы JavaScript, поэтому запустить код на JS можно прямо в браузере. Вот, как это сделать:

Шаг 1. Откройте любой браузер (мы будем использовать Google Chrome).

Шаг 2. Откройте инструменты разработчика. Для этого щелкните правой кнопкой мыши на пустой области и выберите пункт «Просмотреть код» (Inspect). Горячая клавиша: F12.

Шаг 3. В инструментах разработчика перейдите на вкладку «Консоль» (Console). Здесь уже можно писать код на JavaScript. Попробуйте ввести console.log(«Hello, world!») и нажмите Enter, чтобы запустить код.

С помощью Node.js

Node — среда выполнения кода JavaScript вне браузера. Вот, как запустить JS с помощью Node.js:

Шаг 1. Установите последнюю версию Node.js.

Шаг 2. Установите IDE или текстовый редактор. Мы будем использовать Visual Studio Code.

Шаг 3. В VS Code перейдите в Файл > Новый файл и напишите код на JS. Сохраните файл с расширением .js. Мы написали программу, которая выводит на экран строку «Hello, world!», поэтому файл будет называться helloworld.js.

Шаг 4. Откройте терминал/командную строку, перейдите к расположению файла (используйте команду cd ). Введите node helloworld.js и нажмите Enter. Вывод появится в терминале.

Примечание. JavaScript-код можно написать и запустить непосредственно в терминале. Для этого просто введите node и нажмите Enter.

С помощью веб-страницы

JavaScript изначально создавали для того, чтобы сделать веб-страницы интерактивными, поэтому JavaScript и HTML идут рука об руку. Вот, как запустить код на JS с помощью веб-страницы:

Шаг 1. Откройте VS Code. Перейдите в Файл > Новый файл. Сохраните файл с расширением .html. У нас это будет main.html.

Шаг 2. Скопируйте doctype, расположенный ниже. Это необходимый для запуска HTML-страницы код. Сохраните скопированный текст в файле.

Шаг 3. Аналогично создайте файл с расширением .js. Напишите в файле следующий JS-код и сохраните его. У нас это будет helloworld.js.

Шаг 4. Вернитесь к файлу main.html и на 11 строке впишите название JS-файла. В нашем случае это будет выглядеть так:

Шаг 5. Откройте main.html с помощью браузера.

Шаг 6. Чтобы проверить, запустился ли ваш JS-код, щелкните правой кнопкой мыши в свободной области, нажмите «Просмотреть код» и перейдите на вкладку «Консоль».

Теперь, когда вы знаете, как запустить JavaScript, приступим к изучению основ JS.

СodeСhick.io — простой и эффективный способ изучения программирования.

2023 © ООО «Алгоритмы и практика»

Источник

Оцените статью