DEV Community

loading...
Cover image for JavaScript Calculator

JavaScript Calculator

andrejarrell profile image Andre Jarrell ・1 min read

Intro

This article will go over creating an efficient and reactive JavaScript Calculator.

JavaScript introduces a global method called eval() that will allow us to calculate expressions.

Vue will keep the app reactive at every button press.

Bootstrap will style our site and keep it fresh.

🛠 Example

We will go over the JavaScript and some of the HTML you need to get started building a Calculator.

⚡ JavaScript

This Vue instance will attach itself to the id attribute of calc. We have supplied methods used to append + clear + calc the input.

new Vue({
    el: '#calc',
    data: {
        input: ''
    },
    methods: {
        append(event) {
            this.input += event.target.innerText;
        },
        clear() {
            this.input = '';
        },
        calc() {
            this.input = eval(this.input);
        }
    }
});
Enter fullscreen mode Exit fullscreen mode

📄 HTML

With Vue we can use conditional rendering to check if the input is empty. The input is reactive so it will update on the page if it changes.

<div v-if="input" class="alert alert-primary text-right">
    {{ input }}
</div>
<div class="alert alert-primary text-right" v-else>
    0
</div>
Enter fullscreen mode Exit fullscreen mode

Here are a few buttons we will be using. Vue will register event listeners for the click event and run the desired methods.

<button class="btn btn-primary" @click="append">3</button>
<button class="btn btn-primary" @click="clear">C</button>
<button class="btn btn-primary" @click="calc">=</button>
Enter fullscreen mode Exit fullscreen mode

👩‍💻 Codepen

You can checkout the finished product here!

📚 Resources

🔗 JavaScript Eval
🔗 Vue
🔗 Bootstrap

Discussion (0)

pic
Editor guide