I'm doing the Udemy course ES6 Javascript: The Complete Developer's Guide
Stephen Grider on my own. This course is my first exposure to javascript. It contains an interesting (to me) exercise on detecting balanced parentheses. I wrote a function with the features I would expect, but I did not use fat arrow functions. I probably did not use other ECMAScript 6 features that I could have used. I would like any suggestions on improving my code.
function balancedParens(inputString){
const errMsg1 = 'ERROR: expression will NEVER be balanced';
const errMsg2 = 'ERROR: unbalanced!';
const successMsg = 'parens are balanced.';
const chars = inputString.split("");
let count = 0;
for ( let i = 0; i < chars.length; ++i ) {
if ( count < 0 ) { console.log(errMsg1); return false; }
if ( chars[i] === "(" ) { ++count; }
else if ( chars[i] === ")" ) { --count; }
}
if ( count < 0 ) { console.log(errMsg1); return false; }
else if ( count == 0 ) { console.log(successMsg); return true; }
else { console.log(errMsg2); return false; }
}
balancedParens("()()(i)"); //correctly returns true
balancedParens("()()())"); //correctly returns false
My function detects parens that can never be balanced and bails out early, which is something the example from the course did not do. I want to retain this feature as I refactor and improve my code.
The course strongly recommends against using for-loops, but I couldn't think of a better way to implement my features. And I couldn't see how using fat arrow functions would improve the code. So I am looking forward to suggestions and feedback.